Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

correct way to return two dimensional array from a function c

Tags:

arrays

c

function

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?

like image 422
Lior Avatar asked Nov 15 '12 02:11

Lior


People also ask

How do you return a two-dimensional array?

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.

Can you return an array in a function in C?

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.

Which is the correct way to declare a 2D array?

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.


1 Answers

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.

like image 181
justin Avatar answered Sep 19 '22 05:09

justin