1

Like a question below, i have to use the pointer concept to copy array from one to another in mystrcpy2 function, unlike mystrcpy function that does not use the pointer concept. Anyway, I typed my answer, " dest = src;" which seemed to be overly simple but right answer for me. But when I type in the input, like "Hello World", it shows like "Hello World ???" like strange letters in the back. But when I type short words like "abc", the result is exactly "abc." Is it simply a matter of computer or did I do something wrong?

I"m also wondering if "while (*src) *dest++=*src++;" works as well?

/*Complete the mystrcpy2() function that copies the null-terminated string pointed by src to the string pointed by dest. The mystrcpy2() should give the same result with the mystrcpy() that uses an index based array traversal approach. Note that adding local variables are not allowed in implementing the mystrcpy2(). Write and submit the source code of your "mystrcpy2()" function. */

#include <stdio.h>
void mystrcpy(char dest[], char src[])
{
    int i=0,j=0;
    while (src[i])
        dest[j++] = src[i++];
}
void mystrcpy2(char *dest, char *src)
{
    dest = src;
}

int main(void)
{
    char mystr1[256];
    char mystr2[256];

    gets(mystr1);

mystrcpy(mystr2, mystr1);
puts(mystr2);

    mystrcpy2(mystr2, mystr1);
    puts(mystr2);
    return 0;
}
Leo Aso
  • 11,898
  • 3
  • 25
  • 46
Nathan Lee
  • 75
  • 1
  • 3
  • 10

1 Answers1

2

Your implementation of mystrcpy2 does not copy anything. In fact, it does nothing at all. When you execute dest = src, you are copying the memory location pointed to by the src variable, not the data at that location. To actually copy the data, you need to deference the pointer, using '*'. So you would do

*dest = *src;

This copies the data from src to dest. But it only copies one character. You need to increment src and dest and then do this again to copy the next character, and you need to keep doing this until you hit the string terminator i.e. until *src == 0. Here's the full implementation.

void mystrcpy2(char *dest, char *src)
{
    while (*src != 0) {
        *dest = *src;
        dest++;
        src++;
    }
    // don't forget to add a terminator
    // to the copied string
    *dest = 0;
}

And here's the exact same thing in a shorter version.

void mystrcpy2(char *dest, char *src)
{
    while (*(dest++) = *(src++));
}
Leo Aso
  • 11,898
  • 3
  • 25
  • 46