top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between a string copy (strcpy) and a memory copy (memcpy)?

0 votes
1,726 views
What is the difference between a string copy (strcpy) and a memory copy (memcpy)?
posted Jan 16, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

4 Answers

+2 votes

strcpy() function copies source string to the destination string and stops copying as soon as '\0' has been moved while memcpy() function works with all kind of data and copy required number of bytes of data.

answer Jan 16, 2015 by Chirag Jain
Almost simultaneous :)
+2 votes

The strcpy function is designed to work exclusively with strings. It copies each byte of the source string to the destination string and stops when the terminating null character (\0) has been moved. On the other hand, the memcpy() function is designed to work with any type of data.

Because not all data ends with a null character, you must provide the memcpy() function with the number of bytes you want to copy from the source to the destination.

answer Jan 16, 2015 by Salil Agrawal
+1 vote

Both are for the string copy but strcpy stops at null character where memcpy is not. Following example will help you to understand the difference in detail -

void dump5(char *str);

int main()
{
    char s[5]={'s','a','\0','c','h'};

    char membuff[5]; 
    char strbuff[5];
    memset(membuff, 0, 5); // init both buffers to nulls
    memset(strbuff, 0, 5);

    strcpy(strbuff,s);
    memcpy(membuff,s,5);

    dump5(membuff); // show what happened
    dump5(strbuff);

    return 0;
}

void dump5(char *str)
{
    char *p = str;
    for (int n = 0; n < 5; ++n)
    {
        printf("%2.2x ", *p);
        ++p;
    }

    printf("\t");

    p = str;
    for (int n = 0; n < 5; ++n)
    {
        printf("%c", *p ? *p : ' ');
        ++p;
    }

    printf("\n", str);
}
answer Dec 20, 2015 by Rajan Paswan
0 votes

**strcpy() copies a string until it comes across the termination character ‘\0’.
With memcopy(), the programmer needs to specify the size of data to be copied.

strncpy() is similar to memcopy() in which the programmer specifies n bytes that need to be copied.

The following are the differences between strcpy() and memcpy():
- memcpy() copies specific number of bytes from source to destinatio in RAM, where as strcpy() copies a constant / string into another string.

  • memcpy() works on fixed length of arbitrary data, where as strcpy() works on null-terminated strings and it has no length limitations.

  • memcpy() is used to copy the exact amount of data, whereas strcpy() is used of copy variable-length null terminated strings.**

answer Feb 26, 2016 by Josita Sarwan
...