Reputation: 575
First of all, I apologize about poor english.
At next simple program,
void fx(int *a){
for(int i=*a; i<='Z'; i++)
printf("%c", i);
}
int main(){
int a;
scanf("%c", &a);
fx(&a);
return 0;
}
I entered a capital letter at run-time, it caused FATAL error and was solved by killing proccess.
It does not cause any problem at next codes.
//except fx()
int main(){
int a;
scanf("%c", &a);
return 0;
}
or
//initialize int a
void fx(int *a){
for(int i=*a; i<='Z'; i++)
printf("%c", i);
}
int main(){
**int a = 0;**
scanf("%c", &a);
fx(&a);
return 0;
}
I know it should be 'char' to input character. but I cannot understand about above situation.
What happened?
PS. I worked with VS2010, c++
Upvotes: 2
Views: 182
Reputation: 1465
You've declared an uninitialized int a, and set it's lower-most byte to something. The result may be a very large number, because the upper-most bytes (whether 16bit or 32bit integers) were left unassigned/uninitialized.
When you passed it to the function, this one will use the full extent of the int a representation. You've then setup a cycle, with stop condition "till it gets to 'Z'", which, by the way, will be correctly promoted to an integer (i.e. all upper-most non-used bytes as 0).
In that cycle you'll be forcing poor printf to try output a byte spanning from 0 to 0xff, several gazillion of times, depending on how long it may take the i to rollover into 'Z'... apparently somewhere in that printf code, someone didn't like non-printable (not just non-ascii) codes.
Upvotes: 2
Reputation: 258568
The difference between this
int a;
scanf("%c", &a);
and this
int a = 0;
scanf("%c", &a);
is that int a;
declares an uninitialized a
. So it can be anything. When you write
scanf("%c", &a);
on an uninitialized int
, you're only setting the topmost bits, because %c
tells scanf
to write the input to a char
, so only the first byte will be written. This can lead to some weird behavior, include what you just stated.
Upvotes: 8