c++ - Why does it cause a run-time error, character to int without initializing? -


first of all, apologize 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 capital letter @ run-time, caused fatal error , solved killing proccess.

it not cause problem @ next codes.

//except fx() int main(){     int a;     scanf("%c", &a);     return 0; } 

or

//initialize int void fx(int *a){     for(int i=*a; i<='z'; i++)     printf("%c", i); } int main(){     **int = 0;**     scanf("%c", &a);     fx(&a);     return 0; } 

i know should 'char' input character. cannot understand above situation.

what happened?

ps. worked vs2010, c++

you've declared uninitialized int a, , set it's lower-most byte something. result may large number, because upper-most bytes (whether 16bit or 32bit integers) left unassigned/uninitialized.

when passed function, 1 use full extent of int a representation. you've setup cycle, stop condition "till gets 'z'", which, way, correctly promoted integer (i.e. upper-most non-used bytes 0).

in cycle you'll forcing poor printf try output byte spanning 0 0xff, several gazillion of times, depending on how long may take i rollover 'z'... apparently somewhere in printf code, didn't non-printable (not non-ascii) codes.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -