如Philip Potter所解释的那样,memcpy的主要区别在于它将复制您要求的所有n个字符,而strncpy将复制到第一个空终止符(包括该终止符)或n个字符为止。如果strncpy复制的字符数少于N个,则会用空字符填充其余部分。
下面的程序将回答您的问题:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char s[10] = "qwerty",str1[10];
int i;
s[7] = 'A';
memcpy(str1, s, 8);
for(i=0;i<8;i++)
{
if(str1[i]!='\0')
printf("%c",str1[i]);
}
return 0;
}
输出:
qwertyA
执行下面的代码并检查差异,你可能会发现它很有用。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char s[10] = "qwer\0ty", str[10], str1[10];
s[7] = 'A';
printf("%s\n",s);
strncpy(str,s,8);
printf("%s\n",str);
memcpy(str1,s,8);
printf("%s\n",str1);
for(int i = 0; i<8; i++)
{
printf("%d=%c,",i,str[i]);
}
printf("\n");
for(int i = 0; i<8; i++)
{
printf("%d=%c,",i,str1[i]);
}
return 0;
}
输出:
qwer
qwer
qwer
0=q,1=w,2=e,3=r,4=,5=,6=,7=,
0=q,1=w,2=e,3=r,4=,5=t,6=y,7=A,
memcpy
和strncpy
,然后体验其中的区别。 - Linus Kleen