【发布时间】:2020-05-30 16:14:24
【问题描述】:
我试图从 C 中的函数返回 2D 整数数组。我能够使用 malloc() 使用动态内存分配返回它,但我无法理解如何使用 static 关键字来做到这一点。
下面是使用static关键字成功返回二维数组的代码sn-p,
int (*(get_2d_arr_using_static)())[10] // Can someone explain me this statement in detail ?
{
static int arr[10][10] = { { 1,2,3}, {4,5,6}, {7,8,9}};
return arr;
}
int main()
{
int (*arr)[10] = get_2d_arr_using_static(); // Need some insights on this statement too
printf("Result ( x: 3, y =3 ): \n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf(" %d", arr[i][j]);
}
printf("\n");
}
}
我需要对评论的陈述进行一些解释。
【问题讨论】:
-
为什么这个标签是c++?这是普通的 C 语言,而不是你在 C++ 中的处理方式。这两种语言非常不同。
-
方便的工具:cdecl.org
-
我这样做是因为大多数 C++ 程序员都有 C 经验,我希望这个问题也能传达给他们。其次,这段代码使用 gcc 和 g++ 给出了准确的输出。所以从技术上讲,它也是有效的 C++ 代码。
-
问这样一个问题的好方法是写下你的想法,陈述你的推理,然后问你是否正确。如果你错了,有人会纠正你。如果你是对的,那就太好了。有人可能会提供更多详细信息或警告,您就可以开始了。
-
@user4581301,谢谢,它确实是一个有用的工具。