Return an array of known size in C ++?

If I can pass an array of known size:

void fn(int(*intArray)[4])
{
    (*intArray)[0] = 7;
}

why I can not return it:

int intArray[4] = {0};
int(*)[4] fn()
{
    return &intArray;
}

here, ")" in "(*)" generates a "syntax error :)".

+5
source share
3 answers

[4] comes after the function name, as happens after the variable name in the variable definition:

int (*fn())[4]
{
    return &intArray;
}

Since this is a very obscure syntax that tends to be confusing for anyone reading it, I would recommend returning the array as simple int*unless you have any special reason why it should be an -to-array pointer.

You can also simplify function definitions with typedef:

typedef int intarray_t[4];

intarray_t* fn() { ... }
+4
source

, .

, :

int fn()[4] {
   ...

-; - Comeau, , :

error: function returning array is not allowed

int**; , , , .

+2

You can return int**

+1
source

All Articles