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

前端 未结 3 1368
慢半拍i
慢半拍i 2021-02-13 21:52

What is the significant difference between memcpy() and strncpy()? I ask this because we can easily alter strncpy() to copy any type of da

相关标签:
3条回答
  • 2021-02-13 22:28

    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 .

    0 讨论(0)
  • 2021-02-13 22:29

    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.

    0 讨论(0)
  • 2021-02-13 22:38

    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.

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