Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the size of a pointer?

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.

like image 783
MGZero Avatar asked Jul 19 '11 17:07

MGZero


People also ask

What size is a pointer in C?

The size of the character pointer is 8 bytes. Note: This code is executed on a 64-bit processor.

Why the size of pointer is 4 bytes?

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.

Is a pointer 4 or 8 bytes?

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.

What is the size of int pointer?

int is 32 bits in size. long , ptr , and off_t are all 64 bits (8 bytes) in size.


2 Answers

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).

like image 143
Jens Avatar answered Sep 28 '22 12:09

Jens


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.

like image 23
Nathan Monteleone Avatar answered Sep 28 '22 12:09

Nathan Monteleone