我在 strncpy()
复制我需要的长度的额外字符时遇到问题。我需要将 10 个最高有效位从一个字符串复制到另一个字符串(均采用 char*
格式)。
较大变量的大小在直觉上并不重要,较小变量仅在它明显小于我需要的值时影响输出(我也不知道为什么会这样)。
我的 strncpy()
中的 n 值可能是导致问题的原因,但我不知道它为什么会这样。如果我没记错的话,目标字符串的长度 n 应该比数据长 1,以解决末尾的空字符。
我的字符串根本不是这样的。将 n
设置为 11
,我收到以下输出:
00000111101100100100001110100000
00000111101
我想它只会复制 10 个字符,最后一个字符为 null。增加 n
会产生相同的结果。
将 n 减少到 10 揭示了问题的核心:
00000111101100100100001110100000
0000011110@
我不知道它为什么会这样做,但随着 n 的减少它会继续这样做,直到 n
小得多(大约 8)。
这些是我的代码的相关行:
char line[11], hexAddr[8], binAddr[33], lv1Index[11];
...
strncpy(lv1Index, binAddr, 10);
在此之前,lv1Index
未被触及,并且 binAddr 直接预先显示(在给定的输出中)。
添加的字符总是@
,所以我不认为它是lv1Index
预初始化的垃圾。
最佳答案
来自 one C++ reference :
If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.
No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.
这意味着你应该把空终止符放在自己身上:
lv1Index[10] = '\0';
关于c - strncpy() 字符串长度输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8207823/