Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return an array of a known size in C++?

Tags:

c++

arrays

return

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 : )".

like image 224
Kay Avatar asked Jun 09 '10 11:06

Kay


2 Answers

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() { ... }
like image 153
sth Avatar answered Sep 24 '22 09:09

sth


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.

like image 30
Will Avatar answered Sep 24 '22 09:09

Will