memcpy 一个子字符串
我想尝试C memcpy功能。我有这样的代码:
char destination[40];
memcpy(destination, "My favorite destination is...", 11);
printf(destination);
我想将前 11 个字母复制到目标数组。当我使用 printf 时,结果是“My favorite2”。为什么?
I would like to try C memcpy function. I have this code:
char destination[40];
memcpy(destination, "My favorite destination is...", 11);
printf(destination);
I woul like to copy first 11 letters to destination array. When I use printf, the result is "My favorite2". Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您在 11 个字符末尾缺少 NULL 终止符 -> Printf 只是打印该内存部分中的所有内容,直到找到 NULL 终止符。
只需添加destination[11] = 0;
那应该有效:)
You are missing the NULL terminator at the end of the 11 characters -> Printf is just printing whatever is in that part of memory until it finds a NULL terminator.
Simply add in destination[11] = 0;
That should work :)
这是因为
memcpy
不会以空字节终止字符串。您可以首先用空值填充整个数组:That is because
memcpy
does not terminate the string with a null byte. You could start by filling the entire array with nulls:C 字符串必须以 null 结尾。最简单的解决方案是首先将 0 复制到整个字符串中。
C strings must be null terminated. Simplest solution is to copy 0's into the whole string first.