简体   繁体   中英

Why am I getting a segmentation fault for this multidimensional array?

I want to create a 2D pointer boolean array, but as soon as I declare it and try to initialize it I get a segmentation fault. I tried only declaring the array and not initializing it, and I've tried initializing the array as well.

I have some functions and global variables in my program, and have tried making everything except my main function, #include , and using namespace std; into a comment but I'm still getting the error: only declaring:

int main(){
    // Variable declarations. You can add more if necessary
    bool **world;
    int nrows, ncols;
    char next;

    cout << "Enter world dimensions (rows and columns): ";
    cin >> nrows >> ncols;


    **world = new bool*[ncols];
    for (int   i = 0; i < ncols; i++) {
      world[i] = new bool[nrows];
    }   

declaring and initializing:

int main(){
    // Variable declarations. You can add more if necessary
    bool **world;
    int nrows, ncols;
    char next;

    cout << "Enter world dimensions (rows and columns): ";
    cin >> nrows >> ncols;


    **world = new bool*[ncols];
    for (int   i = 0; i < ncols; i++) {
      world[i] = new bool[nrows];
    }   
    for (int i = 0; i < ncols; ++i) {
      for (int j = 0; j < nrows; ++j) {
        world[i][j] = false;
      }
    } 

The error is: Segmentation fault (core dumped) .

**world = new bool*[ncols]; is equivalent to world[0][0] = new bool*[ncols]; as world is uninitialised this is undefined behaviour. This only complies as a pointer is convertible to bool. If your array was a different type like int your code wouldn't compile.

What you actually want to do is assign to the pointer:

world = new bool*[ncols];

A std::vector would make your code simpler and safer, this single line replaces all your initialisation code and has no memory leaks:

std::vector<std::vector<bool>> world(ncols, std::vector<bool>(nrows, false));

I'm general multidimensional arrays and vectors have poor performance, you are better off using a single dimensional array and calculating the index with: col * nrows + row

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM