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 : )".
The [4]
goes after the function name, just like it goes after the variable name in a variable definition:
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.
You could also simplify the function definition with a typedef:
typedef int intarray_t[4];
intarray_t* fn() { ... }
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With