我想尝试使用C memcpy函数。我有以下代码:
char destination[40];
memcpy(destination, "My favorite destination is...", 11);
printf(destination);
我想将前11个字母复制到目标数组。当我使用printf时,结果是“My favorite2”。为什么?
您在11个字符的末尾缺少了NULL终止符-> Printf只是打印内存中的内容,直到找到NULL终止符。
只需添加destination [11] = 0;
那应该就可以了 :)
memcpy
不会在字符串末尾添加空字节。您可以先使用零填充整个数组:memset(destination, 0, sizeof destination);
C字符串必须以空字符结尾。最简单的解决方案是先将0复制到整个字符串中。
memset(destination, 0, sizeof(destination));
char destination[40] = { 0 };
就可以实现。 - Jens Gustedtprintf("%.11s","My favorite destination is...");
memcpy
来处理字符串?而不是strncpy
? - Kerrek SBstrncpy(destination, "我最喜欢的目的地是...", 11);
也不会添加 NUL 字节。 - rodrigostrncat
? - Kerrek SBmemcpy
协同工作。 - Jens Gustedt