I have tried this but it won’t work:
#include <stdio.h>
int * retArr()
{
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
return a;
}
int main()
{
int a[3][3] = retArr();
return 0;
}
I get these errors:
Error 3 error C2075: ‘a’ : array initialization needs curly braces
4 IntelliSense: return value type does not match the function type
What am I doing wrong?
A struct is one approach:
then just return the struct by value.
Full example:
The typical problem you face is that
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};in your example refers to memory which is reclaimed after the function returns. That means it is not safe for your caller to read (Undefined Behaviour).Other approaches involve passing the array (which the caller owns) as a parameter to the function, or creating a new allocation (e.g. using
malloc). The struct is nice because it can eliminate many pitfalls, but it’s not ideal for every scenario. You would avoid using a struct by value when the size of the struct is not constant or very large.