Understanding Pointer Sizes in C/C++

Understanding Pointer Sizes in C/C++

·

2 min read

Pointers are essential for managing and manipulating data in memory. One common question that arises is how much memory a pointer itself occupies.

I used to think if a pointer is of integer type it’ll occupy 4 bytes of memory, but seems like that’s not the case.

Pointer Size Depends on System Architecture

First and foremost, the size of a pointer in C and C++ is primarily determined by the architecture of the system on which your code is running. It's independent of the data type to which the pointer points. Here's a simple breakdown:

  • On a 32-bit system: A pointer typically occupies 4 bytes.

  • On a 64-bit system: A pointer typically occupies 8 bytes.

This consistent size for pointers is designed to ensure they can hold addresses for the entire addressable memory space of the system.

Pointer Data Type Doesn't Matter

Whether you declare an int*, double*, char*, or any other type of pointer, the size of the pointer variable itself remains the same on the same architecture. For example, both int* and double* pointers will have the same size on a given system.

Pointer Arithmetic Accounts for Data Type Size

When you perform pointer arithmetic, such as incrementing or decrementing a pointer, the size of the pointed-to data type matters. For instance, if you have an int* and increment the pointer, it moves forward by the size of an int (typically 4 bytes on a 32-bit system and 8 bytes on a 64-bit system).

Conclusion

In conclusion, understanding pointer sizes in C/C++ is straightforward. The size of a pointer depends on your system's architecture, and it's not influenced by the data type it points to. This consistency ensures that pointers can handle addresses for the full memory capacity of your machine.