从函数 c 返回二维数组的正确方法 [英] correct way to return two dimensional array from a function c
问题描述
我已经试过了,但是不行:
I have tried this but it won't work:
#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;
}
我收到这些错误:
错误 3 错误 C2075:'a':数组初始化需要花括号
4 IntelliSense:返回值类型与函数类型不匹配
Error 3 error C2075: 'a' : array initialization needs curly braces
4 IntelliSense: return value type does not match the function type
我做错了什么?
推荐答案
结构是一种方法:
struct t_thing { int a[3][3]; };
然后按值返回结构体.
完整示例:
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;
}
<小时>
你面临的典型问题是int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};您的示例中的 code> 指的是在函数返回后回收的内存.这意味着您的调用者阅读(未定义行为)是不安全的.
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).
其他方法包括将数组(调用者拥有的)作为参数传递给函数,或创建新的分配(例如使用 malloc
).该结构体很好,因为它可以消除许多陷阱,但它并不适用于所有场景.当结构的大小不是恒定的或非常大时,您将避免按值使用结构.
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.
这篇关于从函数 c 返回二维数组的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!