从一个函数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;
}
我得到这些错误:
I get these errors:
错误3错误C2075:'一':数组初始化需要大括号结果
4智能感知:返回值类型不匹配的功能类型
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]; };
然后只是值返回结构。
then just return the struct by value.
完整的示例:
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类型的[3] [3] = {{1,2,3},{4,5,6},{7,8,9}} ;
在你的例子指的是该函数返回后回收内存。这意味着它是不安全的来电者阅读(未定义行为)。
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屋!