tags:

views:

96

answers:

1
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!

+15  A: 

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

paxdiablo
Thank you, Pax! But what is a `"char *``?
A char* is a pointer to a character, typically used in C to point to a sequence of chars terminated by a zero char. "Hello" would be the address of a 6-character block of memory holding 'H', 'e', 'l', 'l', 'o' and '\0' (the null terminator).
paxdiablo
@metashockwave - a pointer (be it `char *` , `int *` , or another type) is similar to an array, and is one of the fundamental concepts of C. It allows you to create more or less arbitrarily complex data structures and pass complex structures or large lists to and from functions without them going out of scope, among other things. In particular, a `char *` is often used to store strings in C.
Chris Lutz
@Pax: I wonder why is char* implicitly convertable to int? Is this standard-compliant?
sharptooth
It's probably because someone doesn't have their warnings up high enough, though the construct gives a warning on the lowest warning level in GCC.
Chris Lutz
c1x: 6.3.2.3 para 6: "Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type." - So basically what happens is totally up to the implementation (since it decides pointer and the various int sizes).
paxdiablo