Assigned variable randomly changes value every time the program is executed (C programming)

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

      

I get a random 8 digit number from the console every time I execute the above code ... I gave X a certain value, but why am I getting a random value every time I execute? Thank!

+2


source to share


1 answer


This is because you are assigning "char*"

(character pointer) to your integer. Did you mean this:

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

      



The symbol pointer "H"

can be placed at any point in memory that the compiler / linker / loader desires (and it can change every time). Then you will 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 symbol 'H'

will always be the same value (assuming you are using the same base character set - obviously this will be different if you compile it on an EBCDIC platform such as System z USS).

+15


source







All Articles