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?
Use Pointer to Pointer Notation to Return 2D Array From Function in C++ As an alternative, we can use a pointer to pointer notation to return the array from the function. This method has an advantage over others if the objects to be returned are allocated dynamically.
C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.
To declare a 2D array, specify the type of elements that will be stored in the array, then ( [][] ) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference.
A struct is one approach:
struct t_thing { int a[3][3]; };
then just return the struct by value.
Full example:
struct t_thing {
int a[3][3];
};
struct t_thing retArr() {
struct t_thing thing = {
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}
};
return thing;
}
int main(int argc, const char* argv[]) {
struct t_thing thing = retArr();
...
return 0;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With