正如标题所示,如何返回如下指针:
xxxxxxx foo() {
static int arr[5][5];
return arr;
}
Run Code Online (Sandbox Code Playgroud)
BTW.我知道我必须至少指定一个维度的大小,但是如何?
Joh*_*ode 14
返回类型是int (*)[5](指向5元素数组的指针int),如下所示
int (*foo(void))[5]
{
static int arr[5][5];
...
return arr;
}
Run Code Online (Sandbox Code Playgroud)
它崩溃了
foo -- foo
foo( ) -- is a function
foo(void) -- taking no parameters
*foo(void) -- returning a pointer
(*foo(void))[5] -- to a 5-element array
int (*foo(void))[5] -- of int
Run Code Online (Sandbox Code Playgroud)
请记住,在大多数情况下,"N元素数组T" 类型的表达式将转换为"指向T"的类型.表达式的类型arr是"5元素数组的5元素数组int",因此它被转换为"指向5元素数组的指针int",或者int (*)[5].
Pau*_*l R 13
它有助于为此使用typedef:
typedef int MyArrayType[][5];
MyArrayType * foo(void)
{
static int arr[5][5];
return &arr; // NB: return pointer to 2D array
}
Run Code Online (Sandbox Code Playgroud)
如果由于某种原因你不想使用typedef,或者只是对上面函数的裸版看起来很好奇,那么答案是这样的:
int (*foo(void))[][5]
{
static int arr[5][5];
return &arr;
}
Run Code Online (Sandbox Code Playgroud)
希望您能明白为什么使用typedef对于这种情况是个好主意.
| 归档时间: |
|
| 查看次数: |
5537 次 |
| 最近记录: |