correct way to return two dimensional array from a function c

A struct is one approach:

struct t_thing { int a[3][3]; };

then just return the struct by value.

Full example:

struct t_thing {
    int a[3][3];
};

struct t_thing retArr() {
    struct t_thing thing = {
        {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        }
    };

    return thing;
}

int main(int argc, const char* argv[]) {
    struct t_thing thing = retArr();
    ...
    return 0;
}

The typical problem you face is that int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; in your example refers to memory which is reclaimed after the function returns. That means it is not safe for your caller to read (Undefined Behaviour).

Other approaches involve passing the array (which the caller owns) as a parameter to the function, or creating a new allocation (e.g. using malloc). The struct is nice because it can eliminate many pitfalls, but it's not ideal for every scenario. You would avoid using a struct by value when the size of the struct is not constant or very large.


We can solve it by using Heap memory / memory allocating using stdlib :

Allocating memory using stdlib can be done by malloc and calloc.

creating array:

  • int  ** arr=( int * * ) malloc ( sizeof ( int * ) * 5 ); 
    
    is for allocating 5 rows.
  • arr[i]=(int *)malloc(sizeof(int)*5);
    
    is for allocating 5 columns in each "i" row.
  • Thus we created arr [ 5 ] [ 5 ].

returning array:

  • return arr;
    

We just need to send that pointer which is responsible for accessing that array like above.

#include<stdio.h>
#include<stdlib.h>
int **return_arr()
{
    int **arr=(int **)malloc(sizeof(int *)*5);
    int i,j;
    for(i=0;i<5;i++)//checking purpose
    {
        arr[i]=(int *)malloc(sizeof(int)*5);
        for(j=0;j<5;j++)
        {
            arr[i][j]=i*10+j;
        }
    }
    return arr;
}
int main()
{
    int **now;
    now=return_arr();
    int i,j;
    for(i=0;i<5;i++)
    {
        for(j=0;j<5;j++)
        {
            printf("%d ",now[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Tags:

C

Arrays

Function