从函数c返回二维数组的正确方法

Lio*_*ior 6 c arrays function

我试过这个,但它不起作用:

#include <stdio.h>

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

    int main()
    {
    int a[3][3] = retArr();
    return 0;
    }
Run Code Online (Sandbox Code Playgroud)

我收到这些错误:

错误3错误C2075:'a':数组初始化需要大括号
4 IntelliSense:返回值类型与函数类型不匹配

我究竟做错了什么?

jus*_*tin 9

结构是一种方法:

struct t_thing { int a[3][3]; };
Run Code Online (Sandbox Code Playgroud)

然后只按值返回结构.

完整示例:

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;
}
Run Code Online (Sandbox Code Playgroud)

您遇到的典型问题是int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};在您的示例中指的是在函数返回后回收的内存.这意味着调用者读取(Undefined Behavior)是不安全的.

其他方法涉及将数组(调用者拥有的)作为参数传递给函数,或者创建新的分配(例如使用malloc).结构很好,因为它可以消除许多陷阱,但它并不适合每种情况.当结构的大小不是常数或非常大时,您将避免使用struct by value.

  • +1:从seg-fault到纠正的最快方式.很好的答案. (3认同)