scanf and keeping char as an integer

浪子不回头ぞ 提交于 2019-12-24 16:35:18

问题


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]

回答1:


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 pf 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.



来源:https://stackoverflow.com/questions/17643453/scanf-and-keeping-char-as-an-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!