memcpy()和strcpy()有什么区别?我试图在一个程序的帮助下找到它,但两者都提供相同的输出.
int main()
{
char s[5]={'s','a','\0','c','h'};
char p[5];
char t[5];
strcpy(p,s);
memcpy(t,s,5);
printf("sachin p is [%s], t is [%s]",p,t);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产量
sachin p is [sa], t is [sa]
Run Code Online (Sandbox Code Playgroud)
egr*_*nin 118
怎么办才能看到这种效果
编译并运行此代码:
void dump5(char *str);
int main()
{
char s[5]={'s','a','\0','c','h'};
char membuff[5];
char strbuff[5];
memset(membuff, 0, 5); // init both buffers to nulls
memset(strbuff, 0, 5);
strcpy(strbuff,s);
memcpy(membuff,s,5);
dump5(membuff); // show what happened
dump5(strbuff);
return 0;
}
void dump5(char *str)
{
char *p = str;
for (int n = 0; n < 5; ++n)
{
printf("%2.2x ", *p);
++p;
}
printf("\t");
p = str;
for (int n = 0; n < 5; ++n)
{
printf("%c", *p ? *p : ' ');
++p;
}
printf("\n", str);
}
Run Code Online (Sandbox Code Playgroud)
它会产生这个输出:
73 61 00 63 68 sa ch
73 61 00 00 00 sa
Run Code Online (Sandbox Code Playgroud)
你可以看到"ch"被复制了memcpy(),但没有strcpy().
Yan*_*min 71
strcpy遇到NULL时停止,'\0'不会.你没有在这里看到效果,因为memcpy在printf中也停止在NULL.
fbr*_*eto 12
strcpy找到源字符串的null终止符时终止.memcpy需要传递大小参数.如果您在printf两个字符数组找到null终止符后,您所呈现的语句正在暂停,但您也会在其中找到t[3]并t[4]复制数据.
strcpy 将字符从源复制到目标,直到它在源中找到NULL或'\ 0'字符.
while((*dst++) = (*src++));
Run Code Online (Sandbox Code Playgroud)
其中作为memcpy从源到给定的大小为n的目的地的数据复制(未字符),而不管数据源.
memcpy如果你知道源包含非字符,则应该使用.对于加密数据或二进制数据,memcpy是理想的方式.
strcpy已弃用,请使用strncpy.