This only fixes the compiler error
The compiler is already giving you the correct type to return, you just need to give the type a name to return it easily:
typedef int (*myArrayPtr)[2];
myArrayPtr myFunc() {
int foo[2][2];
return foo; //Compiles, BUT DON'T USE IT (see below)
}
Alternatively, you can write the function declaration like this (but please don't, this should only be done in code that tries to win the International Obfuscated C Code Contest):
int (*myFunc())[2] {
int foo[2][2];
return foo; //Compiles, BUT DON'T USE IT (see below)
}
This approach actually works
The code above returns a pointer to a local variable, which is automatically deallocated when myFunc()
returns. If the calling function uses the returned pointer in any way, anything might happen. To return a 2D array correctly, you need to malloc()
it:
typedef int myArray[2];
myArray* myFunc() {
myArray* foo = malloc(2*sizeof(*foo));
foo[1][1] = 7;
return foo;
}
Note, that one of the two dimensions is encoded in the array type, while the other one is implicit in the pointer. That is why the sizeof
of *foo
must be multiplied by the size of the first dimension. Of course, you can also encode both dimensions in the array type, but that requires you to write an additional dereference when you access its elements:
typedef int myArray[2][2];
myArray* myFunc() {
myArray* foo = malloc(sizeof(*foo));
(*foo)[1][1] = 7;
return foo;
}