简体   繁体   中英

strcopy function using pointers not working

I need to make a function that receives two char pointers and copies the contents of one into the other, and then returns the beginning of the pointer. I have been messing with this for a couple hours now and have read 100 examples that are all different. Here is what I have right now:

char * mystrcpy(char * dest, char * src) {
        while(1) {
          if(*src == '\0') {
            *dest = '\0';
            return dest;
          }
          else {
            *dest = *src;
            *src++;
            *dest++;
          }
        }

What you want is to increment the pointers, while you actually increment the character that they point to.

Change

*src++;
*dest++;

to:

src++;
dest++;
dest++;

dest is a pointer and you are moving it in order to copy values from src So when you return dest it is already pointing to end of the string.

So don't move this pointer just copy values to it using indexing.

int i=0;
while( *src)
{
    dest[i] = *src;
    i++;
    src++;
}

dest[i] = '\0';

return dest;

So even if you fix *dest++ to dest++ what you return will not give the expected results.

these two lines:

    *src++;
    *dest++; 

should be:

    src++;
    dest++;

Notice no de-reference of the pointers as the code needs to increment the pointers, not what the pointers are pointing to.

And it would be a good idea to save the initial value of dest, so it can be returned. And to avoid losing any string already in the dest buffer, I suspect the value (after saving) of dest needs to be incremented by dest += strlen(dest);

so a concentation of the two strings occurs rather than overlaying the initial string in dest.

Before that function is called, there should be a check that the dest buffer is long enough to hold the strlen() of both strings +1.

+1 is to allow for the termination byte.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM