STRLEN printf on two lines? [closed]
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
精彩评论