Beginners Guide To Pointers

Beginners Guide To Pointers

Pointers can be tricky to understand in the beginning, this guide will help you visualize what pointers are and why are they useful.

Before understanding pointers, let's understand how variables are stored in the memory address. Consider memory address as a continuous block that can store data, memory address can be physical or virtual in nature.

Pointers as the name suggest point to something, it points to a memory address. The memory address will contain some value, therefore the pointer is a variable that contains the address of the value it is pointing to.

Pointers explained

Let's see the example to understand, b is a pointer to a as, b contains the address of the a. & gives us the address of the operand. In our example, a is stored in the memory address of 0x03 and since b = &a, the value of b is 0x03. In order to get the value stored at the address, we use the * operator. b contains the value of the address, which in our case is 42. (*) is called indirection operand and also called dereferencing.

So, now we know, what pointers are, let's see when pointers are useful.

  • Since pointers are the address of an item, they're small. The actual object can be very large and copying them can be both memory and time expensive. Pointers take up only the space of an address and since they're small, sending and storing them to a function is cheap.
  • Pointers allow you to refer to the same space in memory from multiple locations. This means that you can update the memory in one location and the change can be seen from another location in your program.
  • The address of the first element in your array can be assigned to a pointer. This then allows you to access the underlying allocated bytes directly. The whole point of an array is to avoid you needing to do this though.

Pointer (computer programming) - Wikipedia
Memory address - Wikipedia