-1

I am trying to define a 2D array, but I want to do it in a function,

here is my code:

int** createArray( int columns, int rows)
{   
    int** array[rows];
    for(int i = 0; i < rows; i++)
    {
        array[i] = new int*[columns];
    }

    for(int i = 0; i <columns; i++)
    {
        for(int j = 0; j < rows; j++)
        {
            array[i][j] = 0;
            std::cout <<array[i][j];
        }
        std::cout<<"\n";
    }
    return *array;
}

int main()
{
    
int **myArray = createArray(3,5);


for(int k =0; k < 5; k++)
{
    if( (myArray[0][k] == 0) && (&myArray[1][k] == 0)) //segmentation fault
    {
        myArray[2][k] = 10; //segmentation fault
    }

delete[] myArray;
}

But it causes errors which can be seen as comments in lines. I am new to C++ and I do not know how to fix this.

Thank you very much

Mechatrnk
  • 101
  • 1
  • 13
  • 1
    The error is self explanatory. You have mentioned `int` as the return type of `createArray` function(have a look at how to write function signatures). Change it to the type of variable `array` – Cherubim Sep 30 '20 at 10:40
  • Thank you but as I say, I am new to C++ so for me the error is not self-explanatory, how could I fix it? I tried to change the function type to void but now I cannot give to the created array a name – Mechatrnk Sep 30 '20 at 10:48
  • 1
    What @Cherubim says is to change the return type of `createArray` to `int**`. You must always return what you promise to return! – Botje Sep 30 '20 at 10:52
  • @Botje Except that `array` in `createArray` is not `int**` nor convertible to that. – Yksisarvinen Sep 30 '20 at 11:01
  • @Mechatrnk Don't mess with `new` and `delete` yourself please. That's not intended in c++, but what standard container classes (i.e. `std::vector`, `std::array`) are for. – πάντα ῥεῖ Sep 30 '20 at 11:01
  • @Yksisarvinen oh, hah. missed that. I was just looking at the createArray call. – Botje Sep 30 '20 at 11:02

1 Answers1

0

Prefer std::vector over manual memory management:

std::vector<std::vector<int>> createArray(int columns, int rows)
{   
    return std::vector<std::vector<int>(rows, std::vector<int>(columns));
}

int main()
{
    int COLUMNS = 5;
    int ROWS = 3;
    auto myArray= createArray(COLUMNS, ROWS); 

    /*
    Do stuff
    */

    //std::vector handles delete on it's own, no need to clean up
}

If you cannot use std::vector for some reason, this is the a way to initialize 2D array on the heap:

int** createArray(int columns, int rows)
{   
    int** arr = new int*[rows];
    for(int i = 0; i < rows; ++i) 
    {
        arr[i] = new int[columns];
    }

    return arr;
}

int main()
{
    int COLUMNS = 5;
    int ROWS = 3;
    int** myArray= createArray(COLUMNS, ROWS); 

    /*
    Do stuff
    */

    //you need to a delete for every new and delete[] for every new[]
    for(int i = 0; i < rows; ++i)    
    {
        delete[] myArray[i];
    }
    delete[] myArray;
}
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52