How to return a 2D array from a function in C? How to return a 2D array from a function in C? arrays arrays

How to return a 2D array from a function in C?


In C, pointers and arrays are closely related. Also, you usually need to pass the size of an array as a separate variable. Let's start you with:

#include <stdio.h>float** createArray(int m, int n){    float* values = calloc(m*n, sizeof(float));    float** rows = malloc(m*sizeof(float*));    for (int i=0; i<m; ++i)    {        rows[i] = values + i*n;    }    return rows;}void destroyArray(float** arr){    free(*arr);    free(arr);}void drawLine(const float** coords, int m, int n);int main(void){    float** arr = createArray(2,2);    arr[0][0] = 1;    arr[0][1] = 1;    arr[1][0] = 2;    arr[1][1] = 2;    drawLine(arr, 2, 2);     destroyArray(arr);}


In C/C++, when you pass an array to a function, it decays to be a pointer pointing to first element of the array. So, in pixels() function, you are returning the address of a stack allocated variable. The returning variable's address is no longer valid because on pixels() return, the stack allocated variable goes out of scope. So, instead you should for a variable whose storage is dynamic ( i.e., using malloc, calloc ).

So, for a two dimensional array, you may use float** arrayVariable;. Also, if you passing this to a function, you should be wary of how many rows & columns it has.

int rows, columns;float** pixels(){    // take input for rows, columns    // allocate memory from free store for the 2D array accordingly    // return the array}void drawLine( float** returnedArrayVariable ){  //drawing the line}

Since, 2D array is managing resources it self, it should return the resources back to the free store using free.


Thank you all for your answers and more specifically for the detailed explanation of the array-pointer relationship.

I encapsulated the array in a structure

 struct point_group1 {        float x[3];        float y[3];};struct point_group1 pixels(){    struct point_group1 temp;    temp.x[0] = 0.0;    temp.x[1] = 1.0;    temp.x[2] = -1.0;    temp.y[0] = 0.0;    temp.y[1] = 1.0;    temp.y[2] = 1.0;    return temp;    }struct point_group1 points1  = pixels();axPoly(points1.x, points1.y ,3, 0.0);