Soywod Soywod - 1 month ago 7
C Question

Why and when should we use pointer-to-pointer instead of simple pointers in C?

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) ?

Answer

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().

void* new_copy_of_page( const void* const old_page )
/* Copies the page of memory at old_page to a new page of memory (aligned to
 * the page size).  This new page must be freed with free().  Returns a pointer
 * to the new page, or NULL if out of memory.
 */
{
  void *new_page = NULL; // Set by posix_memalign() to a new memory page.

  assert(old_page); // Check for valid input. 

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

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

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

Comments