Pointers are FUN!
For a month now, I got introduced to pointers in C. I had no idea there was such I thing. I know 😮💨
A pointer is a variable that stores the memory address of another variable.
It points to the location in memory where data of a specific data type is stored. So, while pointers themselves are not a data type, they are used to refer to data of various data types.
We shall write a simple program in C to demonstrate this.
#include <stdio.h>
/**
* main - demonstrate a simple program using
* pointers.
* Return: 0 Always success
*/
int main(void)
{
int num;
int *numptr; /* pointer of type int declared */
numptr = # /* pointer assigned a memory location */
/**
* Let us see what is stored in the pointer
* is it the same as the memory address of num?
*/
printf("Memory location of num = %p\n", &num);
printf("Value stored in numptr = %p\n", numptr);
return (0);
}
The result for running this program:
Memory location of num = 0x7fff63fa10bc
Value stored in numptr = 0x7fff63fa10bc
What is the purpose of storing memory location?
Memory locations allow you to access and manipulate data stored in memory. By storing the memory address of a variable or data structure, you can retrieve and modify its contents directly, without having to make a copy of the data.
Of course, there are many other uses of storing memory location but for our context. This is what we need to understand.
How can we manipulate data stored in memory?
I will show an example from the same program we wrote up there to help you make sense of this.
#include <stdio.h>
/**
* main - demonstrate a simple program using
* pointers.
* Return: 0 Always success
*/
int main(void)
{
int num;
int *numptr; /* pointer of type int declared */
numptr = # /* pointer assigned a memory location */
/**
* Let us see what is stored in the pointer
* is it the same as the memory address of num?
*/
printf("Memory location of num = %p\n", &num);
printf("Value stored in numptr = %p\n", numptr);
/**
* changing the value of num using a pointer
* We shall apply dereferencing
*/
*numptr = 26;
/**
* we have dereferenced numptr to pass a value to num
* lets look at what is stored in num now
*/
printf("num = %d\n", num);
return (0);
}
Now we have introduced a new concept called dereferencing, well before it spins your head, let us see the result of this code.
Memory location of num = 0x7fff731ff83c
Value stored in numptr = 0x7fff731ff83c
num = 26
What is dereferencing?
Dereferencing a pointer in programming means accessing the value that is stored at the memory location pointed to by the pointer. In simpler terms, it means using a pointer to get the actual data it's pointing to.
Dereferencing is typically done using the * (asterisk) operator in most programming languages.
Conclusion
With a little practice, this concept becomes easier and easier to understand. Did you know there are pointers to pointers!?
We shall discuss that on the next article. Happy learning 😊