correct way to return two dimensional array from a function c

前端 未结 7 621
迷失自我
迷失自我 2020-12-10 06:35

I have tried this but it won\'t work:

#include 

    int * retArr()
    {
    int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    return a;
    }

           


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 06:51

    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
    #include
    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;
    }
    

提交回复
热议问题