gpt4 book ai didi

c - strcpy 与 memcpy

转载 作者:太空狗 更新时间:2023-10-29 16:16:13 28 4
gpt4 key购买 nike

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;
}

输出

sachin p is [sa], t is [sa]

最佳答案

what could be done to see this effect

编译并运行这段代码:

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);
}

它将产生这样的输出:

73 61 00 63 68  sa ch
73 61 00 00 00 sa

你可以看到“ch”被memcpy()复制,而不是strcpy()

关于c - strcpy 与 memcpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2898364/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com