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;
}

1 Answers1

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
  • 148
  • 1
  • 10