
If you started with Python or JavaScript, pointers sound like arcane dark magic for grey-bearded systems engineers. Learn C++ in college and you remember struggling with segmentation faults and memory leaks.
Here is the secret. A pointer is just a variable. Its value is a number. That number holds the address of something else.
To understand pointers, you first need to know where your data lives.
When your code runs, your data has to go somewhere. It lands in the Stack or the Heap.
Imagine the Stack as a stack of sticky notes on your desk.
If you have a variable int a = 10;, it usually sits here. It is fast and safe.
The Heap is a giant warehouse.
A pointer is simply a signpost.
If you have a variable score = 99 on the Heap (at address 0x1234), a pointer is a tiny variable on the Stack that says "The data is at 0x1234".
int score = 99; // The actual value
int *p = &score; // The pointer 'p' holds the address of 'score'p is the address. It tells you where the data sits. *p is the value, the thing stored at that address.
Why not just pass values around and let the language handle the mess?
Imagine you have a 10MB image. Pass it to a function process(image) and your language copies it. You just burned 10MB of RAM and CPU time copying pixels. With a pointer, you pass the address (8 bytes). The function knows where the image is and goes to look at it.
Pass a variable by value and the function gets a clone. Changes to the clone leave the original alone. With a pointer, the function knows where the original lives. It can modify the actual data.
Linked lists, trees, and graphs are just chunks of data holding pointers to other chunks of data. You cannot build them easily without references.
Pointers are not free.
Pointers are the bridge between your code and the hardware. Even when you write high-level JavaScript or Python, the objects you touch are references under the hood. That is why a = b points a at the same data as b.
© Melvin Laplanche - All rights reserved.