c / intermediate
Snippet
Pointer Modification via Double Indirection
To change the address a pointer in the caller's scope points to, you must pass a pointer to that pointer (double indirection). This allows functions to update external pointers, such as during memory reallocation.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdlib.h>void reallocate_buffer(int **ptr, int new_size) {*ptr = realloc(*ptr, new_size * sizeof(int));}int main() {int *buf = malloc(5 * sizeof(int));reallocate_buffer(&buf, 10);free(buf);return 0;}
Breakdown
1
int **ptr
Parameter representing a pointer to an integer pointer.
2
*ptr = realloc(...);
Dereferences the double pointer once to update the original pointer's address.