I need help looking for the source of an error that's plaguing me in my coding assignment (I'm doing the class online over the summer.). The professor is tasking the class with several cstring functions in c++: strlen, strcmp, strcpy, strcat, and strrchr. He wants us to assume those functions don't exist and to make them up from scratch. He has a test file for us to use and see if they work. My problem right now is with strcpy.
test code
void testmystrcpy(void)
{
char pc[MAX_STRING_LENGTH];
char* pcResult;
cout << pc << endl;
pcResult = mystrcpy(pc, "Ruth");
cout << pc << endl;
cout << *pcResult << endl;
ASSURE(pcResult != NULL);
ASSURE(pcResult == pc);
ASSURE((pcResult != NULL) && (strcmp(pc, "Ruth") == 0));
pcResult = mystrcpy(pc, "");
ASSURE(pcResult != NULL);
ASSURE(pcResult == pc);
ASSURE((pcResult != NULL) && (strcmp(pc, "") == 0));
}
The problem lies in ASSURE(pcResult ==pc) (lines 10 and 14). The cout statements I put in confirm that mystrcpy(my version of strcpy) changes pc correctly (or so I assume) but pcResult doesn't.
My code for mystrcpy function
char* mystrcpy(char* s1, const char* s2) {
//declares s1 as the destination
char* destinationPtr = s1;
//copies the source to the destination as long as it's not NULL
while ((*destinationPtr++ = *s2++) != 0);
/* //holds the parameters. holdChar1 is the destination, and holdChar2 holds the source and is a constant.
char* holdChar1 = s1;
const char* holdChar2 = s2;
//checks if the source isn't NULL
if (*holdChar2!='\0') {
//while the source isn't NULL, copy the address of the source into the destination. Increase both by one each.
while (*holdChar2 !='\0') {
*holdChar1 = *holdChar2;
holdChar1++;
holdChar2++;
}
}
*/
/* //for when they are equal or if the destination is larger than the source
// else {
//while the source does not equal NULL, copy the address of the source into the destination. Increase both by one each.
while (*holdChar2 != '\0') {
*holdChar1 = *holdChar2;
holdChar1++;
holdChar2++;
}
// }*/
//return the destination
return destinationPtr;
}
The code inside /**/ can be ignored if it's possible. Any help is appreciated. I still have a hard time using pointers.
I tried setting up a pointer equal to a new cstring, but I ended up causing memory leaks so I erased that chunk of code. If dynamic memory is still the way to go, what would be the best way of writing it to ensure I have no problems with memory?
mystrcpyis supposed to return the original value ofs1- a pointer to the beginning of the string, not to the end. Change the last statement toreturn s1;