Is the size pointer different from its representation using printf?

When i do

int k = 9;
printf("sizeof k: %zu \n", sizeof (&k));


I get the size as 8

. But when I do

printf("pointer to k: %p \n", &k);


I receive 0x7fff57e3ba24

. I see it is 12 hex numbers, which means (since 1 hex is 4 bits) the pointer is 48 bits long, which is 6 bytes.

Question: Why is sizeof print 8 for a pointer even though it's only 6 bytes?


source to share

3 answers

Your logic is that if I write

printf("%d", 4); 


and it prints 1 decimal digit which can be stored in 1 byte, then there sizeof(int)

should be 1 byte.

The number is the 0x7fff57e3ba24

same as 0x00007fff57e3ba24

. Just because a number has fewer digits than a type can store doesn't mean it takes up less space.



The pointer is still 8 bytes long, even if most of the significant bits are zero.

While it is possible to "optimize" the data store by eliminating unnecessary bytes, accessing the data will become much more complex and less efficient. Read about aligning data in computer memory.



Leading zeros are irrelevant, since unsigned addresses leading 2 bytes are zeros, hence not printed. You can change the format specifier to print leading zeros.



All Articles