简体   繁体   中英

Segmentation fault with multidimensional arrays

I tried searching through this website for possible answers of why this error is occurring but couldn't find the exact answer.

For this little code, I basically have the program read input from a file. (It reads every single character.) Then store it in a multi-dimensional array (2D) and finally print out the array.

This is my code:

ifstream file;
char gamemap[20][26];
file.open("maze-hard.txt");
if(!file.is_open())
{
    cout << "Error: Cannot open file" << endl;
    return 0;
}

    for(int i = 0; i < 20; i++) 
    {
        for(int j = 0; j < 26; i++)
        {
            gamemap[i][j] = file.get();
            cout << gamemap[i][j];

        }
        cout << endl;
    }

It was somewhat successful, but I got a segmentation fault error. I don't know where the problem lies. Don't go hard on me for this one. I'm not all that advanced in C++.

 for(int j = 0; j < 26; i++)

我会用j++代替i++ j++

在第二个循环中递增j,而不是i;)

While probably not strictly related to this particular segfault, I'd also check to make sure that the read is good for safety.

if(file.good())
{
    gamemap[i][j] = file.get();
    //etc etc
}

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