STRLEN printf 分成两行?
有人可以向我解释以下发生的情况吗?
unsigned int i;
i = strlen("testData");
printf("%d\n", i);
Output:
8
5
为什么要打印额外的 5?
[更新:] 读完评论后,我愚蠢地意识到 5 是从哪里来的,抱歉!
Can someone explain the following occurrence to me?
unsigned int i;
i = strlen("testData");
printf("%d\n", i);
Output:
8
5
Why is it printing the extra 5?
[Update:] After reading the comment, I stupidly realized where the 5 was coming from, sorry!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该代码片段应该只打印 8。除了打印 5 的代码部分之外,还有其他内容
This code snippet should just print 8.There is something else beyond this code section that prints 5
strlen 代表字符串长度。现在,让我们看看...“testData”。
我们数了一下,有 8 个。
现在我是 8。
所以, printf("%d\n", i);
打印 8。
然后你的程序中有一些代码打印 5。不能告诉你为什么,因为我看不到代码
strlen stands for string length. Now, let's see... "testData".
we counted 8.
now i is 8.
So, printf("%d\n", i);
prints 8.
And then later you have some code in your program which prints 5. Can't tell you why because I can't see the code
一种可能的解释是,您有未定义的行为,因为您正在使用有符号整数 (
%d
) 的格式规范,但传递了unsigned int
范围。正确的printf
调用是:虽然不太可能,但一种可能的解释是实现中未定义的行为导致打印额外的 5。
One possible explanation is that you have undefined behaviour because you are using a format specification for a signed integer (
%d
) but passing anunsigned int
parameter. The correctprintf
call would be:Although unlikely, one possible explanation is that the undefined behaviour on your implementation results in the extra 5 being printed.