What is the difference between memcpy() and strncpy() given the latter can easily be a substitute for the former?

ε祈祈猫儿з 提交于 2019-12-04 17:16:40

问题


What is the significant difference between memcpy() and strncpy()? I ask this because we can easily alter strncpy() to copy any type of data we want, not just characters, simply by casting the first two non-char* arguments to char* and altering the third argument as a multiple of the size of that non-char type. In the following program, I have successfully used that to copy part of an integer array into other, and it works as good as memcpy().

 #include <stdio.h>
    #include <string.h>


    int main ()
    {
    int arr[2]={20,30},brr[2]={33,44};
    //memcpy(arr,brr,sizeof(int)*1);
    strncpy((char*)arr,(char*)brr,sizeof(int)*1);
    printf("%d,%d",arr[0],arr[1]);

    }

Similarly, we can make it work for float or other data-type. So what's the significant difference from memcpy()?

PS: Also, I wonder why memcpy() is in string.h header file, given nearly all of the library functions there are related to character strings, while memcpy() is more generic in nature. Any reason?


回答1:


The simple difference is that memcpy() can copy data with embedded null characters (aka the string terminator in C-style strings) whereas strncpy() will only copy the string to the maximum of either the number of characters given or the position of the first null character (and pad the rest of the strings with 0s).

In other words, they do have two very different use cases.




回答2:


Take for example these numbers in your array:

 brr[2]={512,44};

The least significant byte of the first number brr[0] is 0 (512 is 0x200) which would causes 1)strncpy to stop copying. strncpy does not copy characters that follow a null character.

1) To be pedantic (see comments), this holds provided that the implementation has sizeof (int) > 1 .




回答3:


When memory block requires to be copied memcpy is useful and data in the for of string strncpy is meaningful because of the natural advantage of '\0' terminated string. Otherwise both perform same pattern of copy after execution.



来源:https://stackoverflow.com/questions/16553272/what-is-the-difference-between-memcpy-and-strncpy-given-the-latter-can-easil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!