该怎么做才能看到这种效果
编译并运行以下代码:
void dump5(char *str);
int main()
{
char s[5]={'s','a','\0','c','h'};
char membuff[5];
char strbuff[5];
memset(membuff, 0, 5);
memset(strbuff, 0, 5);
strcpy(strbuff,s);
memcpy(membuff,s,5);
dump5(membuff);
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);
}
它将产生以下输出:
73 61 00 63 68 sa ch
73 61 00 00 00 sa
您可以看到“ ch”是由复制的memcpy()
,但不是strcpy()
。