Pointers
Pointers
are special variables which hold addresses to objects
and variables
.
int x = 69;
int y = 420;
int* ptr1 = &x; // (1)!
int *ptr2 = &y; // (2)!
int* temp = NULL; // (3)!
printf("x: %d", *ptr1); // (4)!
printf("y: %d", *ptr2);
// swap the addresses
temp = ptr1;
ptr1 = ptr2;
ptr2 = temp;
printf("y: %d", *ptr1); // (5)!
printf("x: %d", *ptr2); // (6)!
- Both
int* ptr1
andint *ptr1
are valid ways to declare pointers. &
followed by anobject
or avariable
returns the memory address for it.NULL
is amacro
[^1] which is defined using the#define
preprocessor directive
[^1] as a void pointer (#define NULL (void*)0
).*ptr1
means go to the memory location, stored insideptr1
. This processing of accessing the memory location is calleddereferencing
orindirection
.ptr1
was pointing tox
before, now it points toy
.ptr2
was pointing toy
before, now it points tox
.
Void Pointer
There is another type of pointer
called the void pointer
(void*
) which is not supposed to be accessed. Trying to doing so will result into a compilation error.
Pointer Arithmetic
int x = 420;
int* ptr = &x; // (1)!
ptr++; // (2)!
ptr--; // (3)!
ptr = ptr + 1; // (2)!
ptr = ptr - 1; // (3)!
- Points
ptr
tox
. - Increments
ptr
by adding4 bytes
to it (the offset decided by its type which isint
in this case). - decrements
ptr
by subtracting4 bytes
to it (the offset decided by its type which isint
in this case).
Pointers and Arrays
int arr[] = {1, 2, 3, 4}; // (1)!
int *ptr = arr; //(2)!
ptr = ptr + 2; // (3)!
printf("%d\n", ptr[1]); // (4)!
printf("%d\n", ptr[-1]); // (5)!
arr
in itself is just a memory address, it is not a variable.ptr
is assigned the valuearr
which is the start of the memory block represented by thearray
arr
.- Move 2 offsets and points to
3
. ptr[1]
is same as*(ptr + 1)
.ptr[-1]
is same as*(ptr - 1)
. You can have negative indices for the subscript for pointers but not for thearray
arr
.
Valid and Invalid Operations
int* p1;
int* p2;
p1 + p2 // Invalid
p1 - p2 // Valid
p1 * p2 // Invalid
p1 / p2 // Invalid
p1 > p2 // Valid
p1 >= p2 // Valid
p1 < p2 // Valid
p1 <= p2 // Valid
References
- Read more about macros.