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.
The size of the character pointer is 8 bytes. Note: This code is executed on a 64-bit processor.
Size of a pointer is fixed for a compiler. All pointer types take same number of bytes for a compiler. That is why we get 4 for both ptri and ptrc.
Because of this reason we see the size of a pointer to be 4 bytes in 32 bit machine and 8 bytes in a 64 bit machine.
int is 32 bits in size. long , ptr , and off_t are all 64 bits (8 bytes) in size.
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).
Pointers generally have a fixed size, for ex. on a 32-bit executable they're usually 32-bit. There are some exceptions, like on old 16-bit windows when you had to distinguish between 32-bit pointers and 16-bit... It's usually pretty safe to assume they're going to be uniform within a given executable on modern desktop OS's.
Edit: Even so, I would strongly caution against making this assumption in your code. If you're going to write something that absolutely has to have a pointers of a certain size, you'd better check it!
Function pointers are a different story -- see Jens' answer for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With