Why do pointers have fixed size regardless of the type pointed?

7

The space occupied by normal variables ( int , float , double , char ) obeys the type rule: int occupies 4 bytes, float occupies 4 bytes, double occupies 8 bytes etc.

Why do pointers of different type have exactly the same size in bytes (4 bytes depending on your computer's architecture) regardless of pointer type?

    
asked by anonymous 29.06.2017 / 20:45

3 answers

8

Because a pointer contains a memory address, and all memory addresses are the same size.

For example, imagine that your computer's memory looks like a street with several houses side by side, numbered 0, 1, 2, 3 ... (and yes, they start at zero). Each of these houses stores one byte in memory. In addition, you can refer to each of these homes by their address. To represent the address of one of these houses, just the house number, after all, there is only one street in this case.

If you are in a 32-bit architecture (32 bits = 4 bytes), then the last house on the street would be the one with number 4 294 967 295, which corresponds to 2 32 - 1 . This is the same as 4 Gb. Therefore, to represent any memory address (memory up to 4 Gb), you will need 4-byte addresses.

Finally, note that no matter what type of data you store in these boxes, you still need the same number of bytes to represent an address. A pointer to float is nothing more than somewhere in memory of where you want to read or write a float , and a pointer to int is a place where you want to read or write a int . Regardless of what you want to read or write, the referenced boxes are the same and are on the same street, so they have addresses of the same type.

4 Gb of maximum memory is insufficient for most modern computers. Therefore, in 64-bit architectures, addresses have 8 bytes. This is theoretically enough for 8 exbibytes . But obviously, in practice there are no computers with such memory and we are very far from having them. However, if you need anything with more than 4 Gb of memory, the 64-bit architecture is virtually mandatory.

    
29.06.2017 / 20:52
4

Because a pointer holds a memory address , they are all the same size regardless of the type of data the object should be interpreted to at that address.

On a 32-bit platform, the memory addresses have 32 bits, so the pointers all have this size. On a 64-bit platform, memory addresses will eventually have 64 bits, so pointers already have that width to fit the addresses required for when computers have more than 1 TB of main memory ...

    
29.06.2017 / 20:51
3

Pointers always have the same size regardless of the data type because they hold the address of the position where the variable begins. And this address is fixed size according to the architecture in question.

    
29.06.2017 / 20:51