Reputation: 3706
I just can't get it. Char is an integer, right? So I can do
int var;
scanf("%d", &var);
I:[65]
printf("%c", var);
o:[A].
Why is then wrog to do:
char var;
scanf("%d", &var);
I:[A]
printf("%d", var)
O:[-1236778]
Upvotes: 2
Views: 1687
Reputation: 153348
In the second scanf()
scanf("%d", &var);
the scanf()
parsed the print directive %d
. This implies that the argument &var
is expected to be the address to an int
. Instead the address to a char
was given. The size of an int
is certainly larger than the size of a char
. As scanf()
attempts to place an int
size amount into a place meant only for a 'char', strange things can happen for scanf() may place data is places it should not. Trying to put 10 pounds of potatoes in a 5 pound sack.
Further - it appears doubtful that scanf("%d", &var);
successfully read the input "A". scanf()
would see the A
, and since it is not a digit, would give up scanning for textual input that meets an int
definition. Thus your scanf("%d", &var)
likely returned a value of 0
and thus did not place anything in var
. Saving your bacon, for if it did, it would place data in space it should not.
The final printf("%d", var)
is then simply printing out the var
which has never been set, so you get whatever happened to be in char. -1236778
seems unlikely. I suspect that the post does not match the code nor the input/output in some small pace.
Upvotes: 2