tags:

views:

135

answers:

3

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

+1  A: 

You can return int**

Svisstack
Or void*. Both have as much information about the size of the array.
Pete Kirkham
+3  A: 

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() { ... }
sth
hmm, this doesn't work on any of the online compilers
Will
@Will: It works with gcc v3.4.3 and v4.4.1, as well as with Sun cc v5.9, so I'd say it's a problem with those online compilers.
sth
You can use typedef to ease the syntax problems. But really, you are better off returning int**, or even int *.
Arkadiy
@Arkadiy: you're returning a pointer to an array of four ints?
Will
This is what I was after - thanks. I have no reason behind this, I am just fiddling. It occurred to me that doing:int(*a)[4] = fn2();for(int i = 0; i < (sizeof(*a) / sizeof((*a)[0])); ++i) (*a)[i] = ...;is good for two reasons. (1) the array size becomes part of the type so you will not 'easily' overrun its bounds and (2) you don't have to pass the array size around any more. But I agree, the syntax is horrid what with having to dereference all over the place and "int (*fn())[4]"! Still, I think that a judicious comment after that part may mean that the gains outweigh the problems.
Kay
Assuming you don't expect to delete the array, use a reference instead. `int ( for ( int i = 0; i < ( sizeof ( a ) / sizeof ( ( a ) [0] ) ); ++i ) a [ i ] = 8;`
Pete Kirkham
+3  A: 

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.

Will