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?