In this blog post we talk about Double Pointers in C. Also, known as a pointer to a pointer. We go over 3 use cases to fully understand the usage and go in-depth into a use case where a function can allocate memory for the caller.
Double Pointer Example 1
Let’s look at an simple example where we define an integer, a pointer to an int and a double pointer to an int.
Above we define x, *px, and **px. We set x=42, then we point px to the address of x, and point ppx to the address of px. The magic happens on the expression **px = 43 where *ppx dereferences to px and **ppx will dereference px to be 42. This expression changes the value of x from 42 to 43 by having ppx go through px. Thanks to gdb for the ability to see the memory addresses, pointer values and values.
This case is pretty straightforward, however, the use cases I’ve not see very plentiful. One could image that ppx could be changed to point to many different pointers who’s memory is already allocated. The syntax of **ppx could be used for simplicity where we could change ppx and indirectly change the memory that is pointed to. Let’s look at the next examples which are more common.
Double Pointer Example 2
This example is really to help understand Example 3. It skips the functions used in Example 3.
In this example we indirectly assign p by deferencing the double pointer pp. Through the double pointer pp we set the value of the single pointer p.
Double Pointer Example 3
This example solves a common problem where the caller has a pointer to a type and wants to call a function where the result is memory is allocated for that type and the caller’s pointer is pointing to that memory. That’s a mouthful, but it happens. Having another function allocate memory for a caller is common. It happens in C libraries where you see double pointers passed in and the function allocateds memory. Unfortunately, this can’t be done with single pointers and let’s look at the example below to see why.
We can see from the example above for a function to allocate memory and assign the callers pointer to that memory the double pointer is required. This case is quite common and should be understood for any good C programmer. This example will shed light on what is going on inside many libraries that allocate memory for the caller.