I remember when I was first introduced to pointers in C++. Many resources acknowledged that pointers could be challenging to grasp initially. I, too, found them somewhat confusing at the start. Even after I thought I had understood them, I struggled to discern what made them so special. It wasn't until I spent years in university and the workplace, working extensively with C++, that the true significance of pointers began to crystallize.
Let's return to the basics and illustrate what pointers are and what they do with simple examples. To do this, we need to delve into the concept of computer memory—surprise, surprise! However, I'll provide a highly simplified explanation of memory in a computer.
Lets look at our memory example:
Imagine our computer's memory as an extensive array capable of holding data. This array begins at address 0x01 and, in our case, concludes at address 0x09.
Lets say we create an array similar to that
int32_t arr[ 9 ]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
If we use the memory from our imaginary memory to map the address to our C++ example then: The address of arr[0] has the value 1 and lives at the address 0x01. The address of arr[1] has the value 2 and lives at the address 0x02. The address of arr[4] has the value 5 and lives at the address 0x05. And so on...
Now, let's create one or more pointers and have them point to specific values in the array:
int32_t* arrPtr1 = &arr[1];
int32_t* arrPtr2 = &arr[4];
With the * syntax we can create a pointer which is pointing to an int32_t and on the rhs of the assignment we can take the address of the value in the array with the ampersand & so &arr[1] means we take the address of the value at position 1.
For the pointers we also have a image:
As we can see the pointer itself are at some random place in memory. But lets look a bit closer at the pointer variable itself.
When we visualize the pointers, they may appear to be at random locations in memory. However, let's take a closer look at the pointer variables themselves. For example, the pointer arrPtr1 resides at address 0x0BEEF and points to the address 0x05. What does "points to" mean? It simply means that the value of the pointer variable is the address of the variable it's pointing to.
And thats the main part of the magic with pointers. The value is always the address it is pointing to and thats it. The pointer (as shown in the left-side image) has the following properties:
Now, let's explore how to access the value of a pointer. This can be achieved easily with the * operator placed in front of the pointer's name:
std::cout << *ptr << std::endl;
In the same way you can change the value of the pointer.
Understanding pointers takes time and practice. However, the more crucial aspect is comprehending what they can actually achieve. To delve deeper into this, let's continue... To be continued....