Multiple Pointers Pointing to One Memory Address

5

C lets you do something that might look messy at first glance. You can have multiple pointers referencing the exact same memory location. It isn’t a bug. It’s a feature.

Consider this setup. You declare an integer i. Then you declare three pointers: p, q, and r.

Look at what happens here. p grabs the address of i. q does the same. r doesn’t care about i directly. It just copies whatever address p is holding. Since p points to i, r ends up pointing to i too.

After these lines execute, you don’t have three separate variables floating around. You have one variable with four aliases.

  • i
  • *p
  • *q
  • *r

They are all the same thing.

This happens because pointer assignment is a value copy of the address. The right-hand side address moves to the left-hand side variable. No deep copy of the data occurs. Just the memory location is transferred.

There is no limit to this. You can chain as many pointers as you want. a = b; c = b; d = c; It doesn’t matter. They all point to the same spot in RAM.

There is no limit on the number of pointers that can hold and therefore point to the same address.

Why does this matter? It means you can pass references around freely. You can alias data for different parts of your code to use. You can create complex data structures where nodes reference each other.

It also means caution. Change *p to 5. What happens to i? It becomes 5. Change *q? i changes again. All aliases see the same update.

This is basic C. But it’s powerful. And dangerous if you lose track of which pointer is which.