strncpy()
and memcpy()
are the same?
Because of the fact that strncpy()
only accepts char * as parameter,
Icasts the integer arrays to char *.
Why it gets the different output?
Here is My 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? It gives different answer?
You can implement (sort of)
strncpy
withmemcpy
, but the other way around won't work, becausestrncpy
stops at the "end of the string", which doesn't work at all well for data that isn't a C style string (e.g. has zero bytes in it).To write
strncpy
withmemcpy
would be something like this:(Note: The above implementation doesn't work for the case where the
src
string is not terminated correctly - a realstrncpy
does cope with this - it could be fixed in the above code, but it gets quite complicated).