How do I return an array of pointer to structures from a function in C++?

  array-of-structures, c++, null-pointer, return

I am attempting to write a function which returns an array of pointers to my user-defined structure by following the methodology listed here: using calloc on an array of struct, in a function, and while it works in main(), when I try to call it in a function it only returns the data associated with the final layer. I have verified that internally, the null pointer "result" is updated in the for loop. Essentially, the code breaks down to this:

struct matrix = {int8* data, int dimension1, int dimension2}

matrix** function(args){
    matrix** result = (matrix**)calloc(num_layers, sizeof(matrix)); //pointer is NULL
    matrix* tempresult = //(function called that sets the data and dimensions of tempresult)
    for (d = 0; d < num_layers; d++){
        matrix* tempresult = //(function to set data and dimensions of tempresult, updates each loop)
        printf(data of tempresult); //prints in main as valid data

        result[d] = tempresult; //Receives warning C6011: Dereferencing NULL pointer "result"

        printf(data of result[d]); //also prints in main as valid data
   printf(data of result[1]); //prints values of the final layer, result[num_layers-1]
   return result;

I have tested each of the interim values of tempresult and result[d], which are valid as long as they are printed in the for loop. However, when accessed in main() after the function is called, or outside of the for loop, they all match the last layer. I imagine that the issue is concerning the C6011 error dereferencing the NULL pointer "result", but do not know how to resolve it.

Source: Windows Questions C++