correct way to return two dimensional array from a function c

前端 未结 7 607
迷失自我
迷失自我 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 07:05

    In the example given by the OP, it is the easiest to put the array on the stack. I didn't test this but it would be like this.

    #include stdio.h

    void retArr(a[][3]) {
      a[0][0] = 1; a[0][1] = 2; a[0][2] = 3;
      a[1][0] = 4; a[1][1] = 5; a[1][2] = 6;
      a[2][0] = 7; a[2][1] = 8; a[2][2] = 9;
    }
    
    main() {
      int a[3][3];
      retArr(a);
    }
    

    Yeah, this doesn't "return" the array with the return function, but I would suppose that wasn't the intent of the question. The array, a[][], does get loaded, and the loaded a[][] is available in main after retArr() is called, nothing is overwritten.

提交回复
热议问题