Justin O'Brien
Justin O'Brien

Reputation: 77

Difference between printing pointer address and ampersand address

int firstInt =10;
int *pointerFirstInt = &firstInt;


printf("The address of firstInt is: %u", &firstInt);
printf("\n");
printf("The address of firstInt is: %p", pointerFirstInt);
printf("\n");

The above code returns the following:

The address of firstInt is: 1606416332
The address of firstInt is: 0x7fff5fbff7cc

I know that 0x7fff5fbff7cc is in hexadecimal, but when i attempt to convert that number to decimal it does not equal 1606416332. Why is this? Shouldn't both return the same memory address?

Upvotes: 1

Views: 448

Answers (3)

vlad_tepesch
vlad_tepesch

Reputation: 6883

it seems that you are working on an 64bit machine. so your pointer is 64bit long

both (&firstInt and pointerFirstInt) are exactly same. but are displayed differently. "%p" knows that pointers are 64bit and displays them in hexadecimal. "%u" shows decimal number and assumes 32bit. so only a part is shown.

if you convert 1606416332 to hexadecimal it looks like: 0x5FBFF7CC. you see that this is the lower half of the 64bit address.

edit: further explanations:

since printf is a var-arg function all the parametes you give to it were put on the stack. since you put 8 byte on it in both cases. since Pcs using little endian the lower bytes are put on it first. the printf function parses the string and comes to an %[DatatypeSpecifier] point and reads as many bytes from stack as the datatype that is refered by DatatypeSpecifier requires. so in case of "%u" it only reads 4 bytes and ignores the other bytes. Since you wrote "%u" and not "%x" it displays the value in decimal and not in hexadecimal form.

Upvotes: 1

haccks
haccks

Reputation: 106092

The reason for this is lies here:

C11: 7.21.6:

If a conversion specification is invalid, the behavior is undefined.288) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

Upvotes: 2

Sathish
Sathish

Reputation: 3870

From your hexadecimal address-

The address of firstInt is: 0x7fff5fbff7cc

The size of the address is 6 bytes long. But Size of unsignedint is 4 bytes. When you trying to print the address using %u, It will cause undefined behaviour.

So always print the address using %p.

Upvotes: 1

Related Questions