A pointer is essentially a simple integer variable which holds a memory address that points to a value, instead of holding the actual value itself.
The computer’s memory is a sequential store of data,
a pointer points to a specific part of the memory.
Our program can use pointers in such a way that the pointers point to a large amount of memory - depending on how much we decide to read from that point on.
ROLE OF POINTERS
They are used for several reasons, such as:
Strings
Dynamic memory allocation
Sending function arguments by reference
Building complicated data structures
Pointing to functions
Building special data structures (i.e. Tree, Tries, etc…)
Dereferencing / Indirection
Dereferencing is the act of referring to where the pointer points, instead of the memory address.
We are already using dereferencing in arrays - but we just didn’t know it yet.
The brackets operator - [0] for example, accesses the first item of the array.
since arrays are actually pointers, accessing the first item in the array is the same as dereferencing a pointer.
Dereferencing a pointer is done using the asterisk operator *
/* define a local variable a */int a = 1;/* define a pointer variable, and point it to a using the & operator */int * pointer_to_a = &a;printf("The value a is %d\n", a);printf("The value of a is also %d\n", *pointer_to_a);
we used the & operator to point at the variable a
’&’ is the direction/referencing operator
We can also change the contents of the dereferenced variable:
int a = 1;int * pointer_to_a = &a;/* let's change the variable a */a += 1;/* we just changed the variable again! */*pointer_to_a += 1;/* will print out 3 */printf("The value of a is now %d\n", a);