0

I have a function that needs to return a 2d array, I'm new in c++ but I searched a lot and the best I got is that, which gives "error: cannot convert 'int** (*)[3]' to 'int**' in return".

int** initial_state()
{
    int arr[3][3] =
        {
            {0, 0, 0},
            {0, 0, 0},
            {0, 0, 0}}
        ;

    return arr;
}

2 Answers2

2

A better alternative is using std::vector and simply returning vector<vector<int>>. In order to use vector, you need to include the library vector. (#include<vector>)

The code goes as following:

vector<vector<int>> initial_state()
{
    vector<vector<int>> arr
    {
        {0, 0, 0},
        {0, 0, 0},
        {0, 0, 0} 
    };

    return arr;
}

If it is obligatory to use return a 2d array, then you need to declare the array as a dynamic array.

int** initial_state()
{
    //Create an array of pointers with size 3.
    int** arr = new int* [3];

    //Each pointer points to an array with size 3.
    for (int i = 0; i < 3; i++)
    {
        arr[i] = new int[3];
    }

    //Fill the 2d array with values.
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            arr[i][j] = 0;
        }
    }

    return arr;
}
Raya
  • 138
  • 1
  • 9
-1

You can do something like this using the auto keyword, like in this example:

auto make_array() {
    int arr[3][3];
    return arr;
}

It will actually be an array of pointers to ints, but it works.

Eduardo Maroto Campos
  • 1,418
  • 1
  • 4
  • 15
  • Will the compiler really use the actual type of `arr` as the return type (i.e. `int [3][3]`)? Will it not decay to a pointer as usual (i.e. `int (*)[3]`)? If it decays to a pointer, then the OP will still have a major problem, returning a pointer to a local variable. – Some programmer dude May 22 '21 at 23:25
  • Boy oh boy is the asker in for a nasty surprise when they find the answer they selected as correct doesn't work. – user4581301 May 23 '21 at 01:37
  • @user4581301 it does, I set a value to each part of the array, and it didn't give any errors – Eduardo Maroto Campos May 23 '21 at 01:47
  • [You aren't looking hard enough](https://godbolt.org/z/s61s1q1oa) And [watch it crash](https://ideone.com/fkyDyA). – user4581301 May 23 '21 at 02:54