开发者

STRLEN printf on two lines? [closed]

开发者 https://www.devze.com 2023-01-21 11:43 出处:网络
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is not generally applic
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 12 years ago.

Can someone explain the following occurrence to me?

unsigned int i;
i = strlen("testData")开发者_StackOverflow中文版;
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!


strlen stands for string length. Now, let's see... "testData".

1 - 't' 2 - 'e' 3 - 's' 4 - 't' 5 - 'D' 6 - 'a' 7 - 't' 8 - 'a'.

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


One possible explanation is that you have undefined behaviour because you are using a format specification for a signed integer (%d) but passing an unsigned int parameter. The correct printf call would be:

printf("%u\n", i);

Although unlikely, one possible explanation is that the undefined behaviour on your implementation results in the extra 5 being printed.


This code snippet should just print 8.There is something else beyond this code section that prints 5

0

精彩评论

暂无评论...
验证码 换一张
取 消