Can someone explain the output of the 2nd line?
int x=10;
printf("%d\n",x);
printf("%p\n",x);
printf("%p\n",&x);
Output:
10
0000000a
006aff0c
Can someone explain the output of the 2nd line?
int x=10;
printf("%d\n",x);
printf("%p\n",x);
printf("%p\n",&x);
Output:
10
0000000a
006aff0c
In your case, it appears to be treating the value 10
as a pointer and outputting it as an eigth-digit, zero-padded-on-the-left, hexadecimal number(a).
However, as per C11 7.21.6.1 The fprintf function, /9
(all standards quotes below also refer to C11
):
If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
So, literally, anything is permitted to happen. You generally want to avoid undefined behaviour as much as possible, as the behaviour can change between implementations, versions or even the day of the week :-)
There's also technically a problem with your third line. The standard states, in 7.21.6.1 /8
for the p
conversion specifier:
The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.
Since &x
is actually a pointer to int
, this puts it in violation of the same contract. You should probably use something like this instead:
printf ("%p\n", (void*)(&x));
(a) What it actually does is implementation-defined, as per the second sentence in the final quote above. It can basically do anything, provided the implementation documents it, as specified in J.3 Implementation-defined behavior
:
A conforming implementation is required to document its choice of behavior in each of the areas listed in this subclause.