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


what significant difference between memcpy() , strncpy()? ask because can alter strncpy() copy type of data want, not characters, casting first 2 non-char* arguments char* , altering third argument multiple of size of non-char type. in following program, have used copy part of integer array other, , works 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, can make work float or other data-type. what's significant difference memcpy()?

ps: also, wonder why memcpy() in string.h header file, given of library functions there related character strings, while memcpy() more generic in nature. reason?

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

in other words, have 2 different use cases.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -