c++中动态分配2D数组EXC_BAD_ACCESS错误

Dynamically Allocated 2D Array EXC_BAD_ACCESS Error in C++

本文关键字:BAD ACCESS 错误 EXC 数组 动态分配 2D c++      更新时间:2023-10-16

我在我的程序的早期阶段,现在我只是试图初始化一个2D数组来保存所有的破折号,但我一直得到一个ECX_BAD_ACCESS错误。我的代码似乎可以使用方形数组(例如:5x5或6x6),但如果我做10 × 5,我会得到错误。

void readMatrix(char **twoDarray, int &rows, int &cols)
{
std::cout << "Enter number of rows for board";
std::cin >> rows;
std::cout << "Enter number of columns for board";
std::cin >> cols;

//dynamic 2D array initialization
twoDarray = new char*[rows];
for(int i = 0; i < cols; ++i)
    twoDarray[i] = new char[rows];
//set elements of array to dashes
for(int i = 0; i < rows; ++i)
    for(int j = 0; j < cols; ++j){
        twoDarray[i][j] = '-';
        }
//printing the array
for(int i = 0; i < rows; ++i){
    std::cout << "  " << std::endl;
    for(int j = 0; j < cols; ++j)
        std::cout << twoDarray[i][j] << "  ";
}
}

第一个for循环应该从0到#rows,而不是#cols。此外,在同一循环的主体中分配颜色,而不是行。