Reputation: 101
I was playing around with some code for a while :
int n;
char *ptr;
scanf("%d",&n);
ptr = (char *) &n; // pointer to the integer
printf("\na[0]=%p",*ptr); // print the values at the next 4 memory locations
printf("\na[1]=%p",*(ptr+1));
printf("\na[2]=%p",*(ptr+2));
printf("\na[3]=%p",*(ptr+3));
this code gives me a clean output of
FFFFFFFF
FFFFFFFF
FFFFFFFF
FFFFFFFF
for a input of -1 on win32 settings in VisualC++ '12.
However when I compile this code for a x64 architecture i get -
00000000FFFFFFFF
00000000FFFFFFFF
00000000FFFFFFFF
00000000FFFFFFFF
for the same input value of -1. The size of integer is same across both the architectures. My question is why the memory layout is not all F's throughout the 4 locations ?
Upvotes: 1
Views: 195
Reputation: 153507
%p
and *ptr
not behaving as OP expects.
printf("\na[0]=%p",*ptr); // print the values at the next 4 memory locations
ptr
has the value of address of int n
. Note: The type of ptr
is still a pointer to a char
. *ptr
says to dereference ptr
getting a char
. This char
has the 8-bit value of 0xFF as it is one of the bytes of n
, which is certainly 0xFFFFFFFF (-1). This char
is promoted to an int
as it is a varidac parameter to printf()
. Thus 0xFF becomes 0xFFFFFFFF as int
is likely a 4-byte integer on your machine. printf()
sees the %p
format specifier, thus expecting to see a 4-byte pointer in "VisualC++ '12". So that is you output. On "x64", an 8-byte pointer is expected, but only 4 bytes are defined (the 0xFFFFFFFF). The next 4 byte it grabbed are undefined but turn out to be 0x00000000. Thus you get "00000000FFFFFFFF".
The next line printf("\na[1]=%p",*(ptr+1))
simple gets the next char
of n
, which is also 0xFF. And then the same promotion to int
with a value of 0xFFFFFFFF occurs.
Suspect the OP wants
printf("\na[0] = 0x%08X",* ((int *)ptr) ); // print the values at the next 4 memory locations
Upvotes: 1
Reputation: 40829
The p
specifier of printf
expects a void *
. Instead, you're passing an int
(exercise: why is it an int
?), therefore the behaviour is undefined. Use a correct specifier for what you want to print (c
, x
or u
, perhaps?).
Upvotes: 3