strncpy()字符串长度输出错误
我在 strncpy()
复制所需长度的额外字符时遇到问题。我需要将一个字符串的 10 个最高有效位复制到另一个字符串(均为 char*
格式)。
较大变量的大小直观上并不重要,较小变量仅在显着小于我需要的值时才会影响输出(我也不知道为什么会这样)。
我的 strncpy()
中的 n 值可能是导致问题的原因,但我不知道为什么它会这样。如果我没记错的话,目标字符串的长度 n 应该比数据长 1,以考虑末尾的空字符。
我的字符串根本不是这样的。将 n
设置为 11
,我收到以下输出:
00000111101100100100001110100000
00000111101
我想象它只会复制 10 个字符,最后一个为空。增加n
会产生相同的结果。
将 n 减少到 10 揭示了问题的核心:
00000111101100100100001110100000
0000011110@
我不知道为什么它会这样做,但随着 n 减少,它会继续这样做,直到 n 变得更小(大约 8)。
这些是我的代码的相关行:
char line[11], hexAddr[8], binAddr[33], lv1Index[11];
...
strncpy(lv1Index, binAddr, 10);
其中 lv1Index
在此之前未受影响,并且 binAddr 直接预先显示(在给定的输出中)。
添加的字符始终是 @
,所以我不相信它是 lv1Index
预初始化中的垃圾。
I am having a problem with strncpy()
copying an extra character at the length I need. I need to copy the 10 most significant bits from one string to another (both in char*
format).
The size of the larger variable does not intuitively matter, and the smaller only affects the output when it is significantly smaller than the value I need (I don't know why this is either).
The n value in my strncpy()
may be what's causing the problem, but I have no idea why it's acting the way it is. If I'm not mistaken, n, the length of the destination string, should be 1 longer than the data, to account for the null character at the end.
My string is not behaving this way at all. Setting n
to 11
, I receive the following output:
00000111101100100100001110100000
00000111101
I would imagine it would only copy 10 characters, with the final one for the null. Increasing n
produces the same results.
Decreasing n to 10 reveals the heart of the problem:
00000111101100100100001110100000
0000011110@
I don't know why it would do this, but it continues to do this as n decreases, until n
is much smaller (around 8).
These are the relevant lines of my code:
char line[11], hexAddr[8], binAddr[33], lv1Index[11];
...
strncpy(lv1Index, binAddr, 10);
where lv1Index
was untouched before this, and binAddr is displayed (in the given output) directly beforehand.
The added character is always @
, so I don't believe it's garbage from lv1Index
pre-initialization.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自一个 C++ 参考:
其他文档(MSDN、手册页)有类似的信息。
这意味着您应该将空终止符放在自己身上:
From one C++ reference:
Other documentation (MSDN, man page) has similar information.
This means you should put the null terminator on yourself: