开发者

Strange output of this C program

#include<stdio.h>
main()
{
int i;
char c;
for (i=0;i<5;i++){
        scanf("%d开发者_JAVA百科",&c);
        printf("%d",i);
}
printf("\n");
}

I thought it will print 0 1 2 3 4 but it didn't. What's the reason of the strange output?


Undefined Behaviour.

You're attempting to read an int (the "%d" in the scanf call) into an object of type char (the c). Don't do that!


This program exhibits undefined behavior: The type of &c (char *) does not correspond to the type of the scanf arg (%d wants a signed int *).

What is probably happening is that the scanf is writing 4 bytes to the memory location starting at the address of c. Which is only 1 byte long, so the other 3 bytes overwrite the first 3 bytes of i's value. On a little-endian system, that would effectively set i to whatever integer value you enter shifted right by 8 bits.

But, of course, the behavior is undefined. Next time you compile this code, it could do something completely different. A different compiler, or the same compiler with different options, could keep i in a register (where scanf cannot overwrite it) (but it might instead smash the return address on the stack, causing a crash when the program ends), or it could put the values on the stack in the opposite order (same deal), or it could leave 4 bytes on the stack for c (causing no unexpected behavior), or it could detect the situation and abort with an error, or it could even make demons fly out of your nose.


You are reading into c but printing i, so you will see 01234. You probably mean to print c. But that's not enough. c should be declared int because you are reading with format "%d", which expects an int. Either use format hhd or change c to type int


scanf("%d",&c);

should be

scanf("%c",&c);

btw. It will ask you to input value for c in every iteration and then it will print one value of i. What are you getting?


What's the reason of the strange output?

It's because you havn't used scanf properly. When you use "%d", you have to give scanf a pointer to an int, but you gave it a pointer to a char.

Change your char c to int c

(You should also check functions for errors. e.g. scanf will return EOF on end of input. It will also return the count of assigned values. Since you have given it 1 value, &c , you should check that scanf returns 1. If it does not, something bad might have happened)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜