If I can pass in an array of a known size:
如果我可以传入已知大小的数组:
void fn(int(*intArray)[4])
{
(*intArray)[0] = 7;
}
why can't I return one:
为什么我不能归还一个:
int intArray[4] = {0};
int(*)[4] fn()
{
return &intArray;
}
here, the ")" in "(*)" generates "syntax error : )".
这里,“(*)”中的“)”生成“语法错误:)”。
3 个解决方案
#1
4
The [4]
goes after the function name, just like it goes after the variable name in a variable definition:
[4]在函数名之后,就像它在变量定义中的变量名之后:
int (*fn())[4]
{
return &intArray;
}
Since this is very obscure syntax, prone to be confusing to everybody who reads it, I would recommend to return the array as a simple int*
, if you don't have any special reason why it has to be a pointer-to-array.
由于这是非常模糊的语法,容易让每个读它的人感到困惑,我建议将数组作为一个简单的int *返回,如果你没有任何特殊的原因,为什么它必须是一个指向数组的指针。
You could also simplify the function definition with a typedef:
您还可以使用typedef简化函数定义:
typedef int intarray_t[4];
intarray_t* fn() { ... }
#2
2
Its not allowed to return arrays from functions, but there are workarounds.
它不允许从函数返回数组,但有解决方法。
For example, the following code:
例如,以下代码:
int fn()[4] {
...
Doesn't get accepted by the various online compilers; I tried it on the Comeau online compiler, which is considered to be one of the most standard-following of compilers, and even in relaxed mode it says:
不被各种在线编译器接受;我在Comeau在线编译器上尝试过它,它被认为是最标准的编译器之一,甚至在放松模式下它说:
error: function returning array is not allowed
错误:不允许函数返回数组
Another poster suggests returning int**
; this will work, but be very careful that you return heap-allocated memory and not stack-allocated.
另一张海报建议返回int **;这将工作,但要小心你返回堆分配的内存而不是堆栈分配。
#3
1
You can return int**
你可以返回int **
#1
4
The [4]
goes after the function name, just like it goes after the variable name in a variable definition:
[4]在函数名之后,就像它在变量定义中的变量名之后:
int (*fn())[4]
{
return &intArray;
}
Since this is very obscure syntax, prone to be confusing to everybody who reads it, I would recommend to return the array as a simple int*
, if you don't have any special reason why it has to be a pointer-to-array.
由于这是非常模糊的语法,容易让每个读它的人感到困惑,我建议将数组作为一个简单的int *返回,如果你没有任何特殊的原因,为什么它必须是一个指向数组的指针。
You could also simplify the function definition with a typedef:
您还可以使用typedef简化函数定义:
typedef int intarray_t[4];
intarray_t* fn() { ... }
#2
2
Its not allowed to return arrays from functions, but there are workarounds.
它不允许从函数返回数组,但有解决方法。
For example, the following code:
例如,以下代码:
int fn()[4] {
...
Doesn't get accepted by the various online compilers; I tried it on the Comeau online compiler, which is considered to be one of the most standard-following of compilers, and even in relaxed mode it says:
不被各种在线编译器接受;我在Comeau在线编译器上尝试过它,它被认为是最标准的编译器之一,甚至在放松模式下它说:
error: function returning array is not allowed
错误:不允许函数返回数组
Another poster suggests returning int**
; this will work, but be very careful that you return heap-allocated memory and not stack-allocated.
另一张海报建议返回int **;这将工作,但要小心你返回堆分配的内存而不是堆栈分配。
#3
1
You can return int**
你可以返回int **