Using a double pointer for dynamic memory allocation

Question | Jul 26, 2019 | jmiller 

enter image description here

A double pointer is also known as a pointer to a pointer. E.g. an int pointer to pointer is declared as int** ptrptr;. In following code, an int pointer is dynamically assigned memory for a variable number of ints through a function allocate:

int* iptr = nullptr; 
// allocate memory 
auto n = allocate(&iptr);

Once allocate returns, the iptr points to a memory location that holds n number of ints as shown:

enter image description here

Below is the partial implementation of function allocate. It accepts a int** as argument and returns the number or count of ints for which the memory is allocated:

auto allocate(int** dptr) {
   size_t count = getCount(); 
   /*__Allocate Memory__*/  
   return count;

The function getCount above, which is not shown here, could be a function that reads from a database and returns the count of ints for which the memory is to be allocated. You have to select from below choices that correctly allocates memory (or replaces /*__Allocate Memory__*/) in function allocate above (check Explanations for details):

2015 nextptr