How to create a 2D array using a function?

孤人 提交于 2021-02-17 07:06:38

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/64135749/how-to-create-a-2d-array-using-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!