#include<stdio.h>
main()
{
int i;
char c;
for (i=0;i<5;i++){
scanf("%d",&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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This program exhibits undefined behavior: The type of
&c(char *) does not correspond to the type of the scanf arg (%dwants 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 ofi‘s value. On a little-endian system, that would effectively setito 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
iin 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 forc(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.