Cory
Cory

Reputation: 37

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++;
          }
        }

Upvotes: 1

Views: 129

Answers (3)

user3629249
user3629249

Reputation: 16540

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.

Upvotes: 0

Gopi
Gopi

Reputation: 19874

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.

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122493

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

Change

*src++;
*dest++;

to:

src++;
dest++;

Upvotes: 4

Related Questions