c - strncpy() and memcpy() are different? -
strncpy()
, memcpy()
same?
because of fact strncpy()
accepts char * parameter, icasts integer arrays char *.
why gets different output?
here code,
#define _crt_secure_no_warnings #include <stdio.h> #include <string.h> #define size 5 void print_array(int *array, char *name ,int len) { int i; printf("%s ={ ",name); for(i=0; i<len;i++) printf("%d," ,array[i]); printf("}\n"); } int main(void){ char string1[size] = {'1','2','3','4','\0'}; char string2[size], string3[size]; int array1[size] = {1,2,3,4,5}; int array2[size],array3[size]; strncpy(string2,string1,sizeof(string1)); memcpy(string3, string1,sizeof(string1)); printf("string2 =%s \n",string2); printf("string3 =%s \n",string3); strncpy((char *)array2, (char*)array1 , sizeof(array1)); memcpy(array3,array1,sizeof(array1)); print_array(array2,"array2",size); print_array(array3,"array3",size); return 0; }
it turns out
string2 =1234 string3 =1234 array2 ={ 1,0,0,0,0,} array3 ={ 1,2,3,4,5,}
but why? gives different answer?
strncpy((char *)array2, (char*)array1 , sizeof(array1));
casting array1
char *
doesn't want. there no characters @ location, there integers (little-endian seems).
what happening strncpy
copies bytes integer array until reaches 0 byte, pretty soon. on other hand memcpy
doesn't care 0 bytes , copies whole thing.
to put way, strncpy
finds 0 byte "inside" first integer , stops copying; fill destination buffer zeros specified size.
Comments
Post a Comment