Soywod Soywod - 4 months ago 27
C Question

Pointer to pointer utility, and when use it

I understand how pointers to pointers work, but I can't understand why using pointers to pointers over simple pointers, and when using them in C programming (not C++). I've read a lot of posts about it, but I can't found a satisfying answer. All examples I've seen can be turned into a one-level pointer solution. Can someone give an simple example where pointers to pointers are "mandatory" (that can't be done with simple pointers) ?


The first example you’ve probably seen is

int main ( int argc, char **argv )

In this case, argv is a “ragged” two-dimensional array, that is, each row of the array stores a pointer to a one-dimensional array of varying size.

The other common case is the one everyone else has mentioned so far: you want the function to modify a pointer variable. An example of this from POSIX is the function

int posix_memalign(void **memptr, size_t alignment, size_t size);

This function allocates a memory block of at least size bytes, aligned to alignment. But its return value is an error code. The pointer to the newly-allocated block of memory is written to *memptr. An example of usage might be:

static const size_t page_size = 4096; // Could get this value from sysconf().
extern const void* old_page;          // Data to copy.
void *new_page = NULL;                // Set by posix_memalign() to a new memory page.

if ( 0 != posix_memalign( &new_page, page_size, page_size ) )
  exit(EXIT_FAILURE); // Or handle out-of-memory error.

// Otherwise, the allocation was successful.
memcpy( new_page, old_page, page_size );

This is a somewhat contrived example, because the standard library now has aligned_alloc() with the same functionality and a simpler interface.