Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigned variable randomly changes value everytime the program executes (C Programming)

Tags:

c

int x = "H";
printf("x is %i\n", x);

I get a random 8 digit number from the console everytime I execute the above code... I have given X a definitely value, but why do I get a random value at every execution? Thank you!

like image 593
user133466 Avatar asked May 01 '26 03:05

user133466


1 Answers

That because you're assigning a "char*" (character pointer) to your integer. Perhaps you meant this instead:

int x = 'H'; /* <-- Note single quotes, not doubles. */
printf("x is %i\n", x);

The character pointer "H" can be put anywhere in memory the compiler/linker/loader desires (and it can change each time). You then get that memory address stored in x (with possible loss of precision if your pointer data types have more bits than your integers).

However the character 'H' will always be the same value (assuming you're using the same underlying character set - obviously it will be different if you compile it on an EBCDIC platform like System z USS).

like image 144
paxdiablo Avatar answered May 03 '26 16:05

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!