1

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++;
          }
        }
Cory
  • 37
  • 3
  • 1
    You're incrementing chars instead of the pointers that point to them, and failing to keep track of the beginning of the destination string. **Try some simpler exercises first.** – Beta Feb 03 '15 at 03:39
  • http://stackoverflow.com/questions/13460934/strcpy-using-pointers/26317153#26317153 – vinay hunachyal Feb 03 '15 at 04:04

3 Answers3

4

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

Change

*src++;
*dest++;

to:

src++;
dest++;
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • After doing that, what I am returning still does not give me the right output. For example, if i were to give a src as "Hello world" it is returning "" – Cory Feb 03 '15 at 03:48
  • 1
    @Cory You are moving your pointer which is wrong in-order to return the value – Gopi Feb 03 '15 at 03:54
2
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.

Gopi
  • 19,784
  • 4
  • 24
  • 36
0

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.

user3629249
  • 16,402
  • 1
  • 16
  • 17