strcpy vs. memcpy

后端 未结 9 830
梦如初夏
梦如初夏 2020-12-07 08:17

What is the difference between memcpy() and strcpy()? I tried to find it with the help of a program but both are giving the same output.

         


        
相关标签:
9条回答
  • 2020-12-07 08:28

    The main difference is that memcpy() always copies the exact number of bytes you specify; strcpy(), on the other hand, will copy until it reads a NUL (aka 0) byte, and then stop after that.

    0 讨论(0)
  • 2020-12-07 08:30

    The problem with your test-program is, that the printf() stops inserting the argument into %s, when it encounters a null-termination \0. So in your output you probably have not noticed, that memcpy() copied the characters c and h as well.

    I have seen in GNU glibc-2.24, that (for x86) strcpy() just calls memcpy(dest, src, strlen(src) + 1).

    0 讨论(0)
  • 2020-12-07 08:32

    strcpy stops when it encounters a NUL ('\0') character, memcpy does not. You do not see the effect here, as %s in printf also stops at NUL.

    0 讨论(0)
  • 2020-12-07 08:38

    printf("%s",...) stops printing the data when null is encountered, so both the outputs are same.

    The following code differentiates between strcpy and memcpy:

    #include<stdio.h>
    #include<string.h>
    
    int main()
    {
        char s[5]={'s','a','\0','c','h'};
        char p[5];
        char t[5];
        int i;
        strcpy(p,s);
        memcpy(t,s,5);
        for(i=0;i<5;i++)
            printf("%c",p[i]);
            printf("\n");
        for(i=0;i<5;i++)
            printf("%c",t[i]);
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-07 08:44

    strcpy copies character from source to destination one by one until it find NULL or '\0' character in the source.

    while((*dst++) = (*src++));
    

    where as memcpy copies data (not character) from source to destination of given size n, irrespective of data in source.

    memcpy should be used if you know well that source contain other than character. for encrypted data or binary data, memcpy is ideal way to go.

    strcpy is deprecated, so use strncpy.

    0 讨论(0)
  • 2020-12-07 08:45

    Because of the null character in your s string, the printf won't show anything beyond that. The difference between p and t will be in characters 4 and 5. p won't have any (they'll be garbage) and t will have the 'c' and 'h'.

    0 讨论(0)
提交回复
热议问题