Pointers are just a variable that holds a memory address instead of an actual value. They are called pointers because the variable points to another variable in the memory.

In C, we can create a pointer with the type* syntax from an address of a variable:

int x = 10
int* xp = &x //memory address of x

And we can dereference, meaning get the value of the variable that the pointer points at, with the *pointer syntax:

int value = *xp

Void pointers

As we can see, pointers do need the type of the variable they are pointing at when they are created, but we can also assign the type to void:

void* vp;

This is useful since we can then cast the void pointer to any other pointer type

void* vp
 
int num = 10
float fnum = 3.14
 
vp = (int*) &num
vp = (float*) &fnum

This is so useful that the malloc() actually returns a void pointer, in order for it to be then casted to any other type of pointer, so we can reserve memory for any type.

Arrow operator

The arrow operator foo->bar is equivalent to (*foo).bar, i.e. it gets the member called bar from the struct that foo points to.


tags: c