Home > Blockchain >  How to return a pointer to a full array a.k.a int(*)[] to the main function
How to return a pointer to a full array a.k.a int(*)[] to the main function

Time:08-12

My functions purpose is to make a 2d array of integers on the heap. After I create the pointer to a whole array I return the pointer to the whole array to a void*. I feel like there is a better return type but I can't seem to get the write syntax.

Please let me know if I can do a better return type rather than just a void*.

void* create_matrix(int x, int y){
    int i, j, count;
    int(*matrix)[x] = calloc(y, sizeof *matrix); // a pointer to a full array of size x.
    //matrix = address of array
    //*matrix = address of first element of array; *(matrix   1) = address of first element of second array
    //**matrix = element that exists at the first element of array; *(*(matrix   1)   1) = second element of second array = matrix[1][1]
    count = 0;
    for(i = 0; i < y; i  ){
        for(j = 0; j < x; j  ){
            matrix[i][j] =   count;
        }
    }
    for(i = 0; i < y; i  ){
        for(j = 0; j < x; j  ){
            printf("%d\n", matrix[i][j]);
        }
    }
    return matrix;
}

CodePudding user response:

It is possible to do better if you don't return the pointer from the function, but pass its to the function by reference (i.e. pass its address) and initialise it there. For example

void alloc_matrix(int x, int y, int (**pmat)[x])
{
  int (*matrix)[x] = calloc(...);
  ...;
  *pmat = matrix;
}

...
int x = 5;
int y = 6;
int (*matrix)[x]; // important, declare matrix when x is already known
alloc_matrix(x, y, &matrix);

You can also incorporate both dimensions into the matrix type if you want, i.e. int (*matrix)[x][y]. But then you will need to write (*matrix)[i][j] instead of matrix[i][j] which is a bit inconvenient. Although nominally there is one extra level of indirection, both variants should produce the exact same machine code.

CodePudding user response:

You can return a pointer to an array of unspecified size:

int (*create_matrix(int x, int y))[]
{
   ...
}

Which will be compatible with a pointer to a VLA:

int (*a)[x]=create_matrix(x,y);

The array types are compatible because the size is not a constant in both places. This is specified in section 6.7.6.2p6 of the C standard:

For two array types to be compatible, both shall have compatible element types, and if both size specifiers are present, and are integer constant expressions, then both size specifiers shall have the same constant value. If the two array types are used in a context which requires them to be compatible, it is undefined behavior if the two size specifiers evaluate to unequal values

  • Related