Pointer Basics
Pointers are a variable holding the address of another variable of the same data type.
You can use them to create:
- Shared variables between different functions without copying.
- Linked data structures such as linked lists.
Addresses vs Pointers
- You can get the address of a variable using
&
. - You can store that address in a pointer using
*
.
int x = 9;
int *y = &x;
Variable | Address | Value |
---|---|---|
x |
0xA0C1549 | 9 |
y |
0xA0C1549 | 0xA0C1549 |
Pointers have their own addresses as they are a variable that holds an address.
The *
Operator
The star operator has several functions:
-
Multiplication:
a = b * c;
-
Declaring a pointer variable:
int *a;
-
Dereferencing a pointer:
printf("%d", *a);
Dereferencing
This operation follows the pointer’s reference to get the value of its pointee.
printf("%d", *a);
If we didn’t dereference we will just get the value of the pointee’s address.
If you are pointing to a pointer that points to the value (and so on), you need to dereference an appropriate amount of times to get the value you want:
int x = 9;
int *y = &x;
int **z = &y;
printf("%d", **z);
Initialisation
If you are not sure about which variable’s address to assign to a pointer, use:
int *ptr = NULL;
This ensures that the pointer is not pointing to some random place in memory.
Call by Reference
To use a reference to a variable in a function, instead of calling by value, you can use the following:
void incr(int *z) {
(*z)++;
}
int main(void) {
int x = 10;
incr(&x);
printf("&d", &x);
return 0;
}
The brackets need to be used around z: (*z)++
to avoid incrementing the pointer instead of the value.