Topics / Pointers & Memory / Q4
What is a double pointer and when do you need one?
Short answer: A double pointer (int **pp) is a pointer to a pointer. You need one when a function must change which object the caller's pointer points to (because C passes the pointer itself by value), and for arrays of pointers such as char **argv.
#include <stdlib.h>
#include <stdint.h>
int alloc_buf(uint8_t **out, size_t n)
{
*out = malloc(n); /* changes the caller's pointer */
return *out ? 0 : -1;
}
uint8_t *buf = NULL;
if (alloc_buf(&buf, 64) == 0) { /* buf now points to 64 bytes */ }
With a single pointer (uint8_t *out), assigning out = malloc(n) would only change the function's local copy; the caller's buf would still be NULL, and the memory would leak.
Other uses
- Arrays of strings:
int main(int argc, char **argv), whereargv[i]is achar *. - Linked-list operations without special-casing the head:
struct node { int val; struct node *next; };
void remove_val(struct node **pp, int val)
{
while (*pp) {
if ((*pp)->val == val) {
struct node *dead = *pp;
*pp = dead->next; /* works for the head and for inner nodes */
free(dead);
} else {
pp = &(*pp)->next;
}
}
}
pp points to "the pointer that points to the current node": either the list head or some node's next field. Linus Torvalds often cites this as an example of "good taste" in C.
- Dynamically allocated 2-D arrays as an array of row pointers (each row allocated separately), though a single block with index arithmetic is usually better for cache and fragmentation.
Note: int ** is not compatible with a 2-D array int m[3][4]; that decays to int (*)[4].