What is the size of a pointer?

MGZero picture MGZero · Jul 19, 2011 · Viewed 140.2k times · Source

Is the size of a pointer the same as the size as the type its pointing to, or do pointers always have a fixed size? For example...

int x = 10;
int * xPtr = &x;
char y = 'a';
char * yPtr = &y;

std::cout << sizeof(x) << "\n";
std::cout << sizeof(xPtr) << "\n";
std::cout << sizeof(y) << "\n";
std::cout << sizeof(yPtr) << "\n";

What would the output of this be? Would sizeof(xPtr) return 4 and sizeof(yPtr) return 1, or would the 2 pointers actually return the same size? The reason I ask this is because the pointers are storing a memory address and not the values of their respective stored addresses.

Answer

Jens picture Jens · Jul 19, 2011

Function Pointers can have very different sizes, from 4 to 20 Bytes on an X86 machine, depending on the compiler. So the answer is NO - sizes can vary.

Another example: take an 8051 program, it has three memory ranges and thus has three different pointer sizes, from 8 bit, 16bit, 24bit, depending on where the target is located, even though the target's size is always the same (e.g. char).