简体   繁体   中英

run-time error when resizing vector

When I run this program:

#include <iostream>
#include <vector>
using namespace std;


int main()
{
    vector<vector<char> > screen;
    char ch = 'a';
    unsigned col = 100, row = 100;
    if(screen.size() < (unsigned)row)
        screen.resize(row);
    if(screen[row - 1].size() < (unsigned)col)
        screen[row - 1].resize(col);
    screen[9][9] = ch;
    cout<< "hello";
    cout.flush();
}

cout does not print anything and I get this error:

Segmentation Fault (core dumped)

In linux. Is anything wrong in the program?

If col and row have lower numbers there's no problem.

You're resizing screen to row elements, but then you access element row in it. vector s in C++ are, like arrays, 0-based, so valid indexes are 0...row-1 .

Same goes for the inner vectors and col .

The fact that it works for smaller numbers is an (unfortunate) mishap.

if(screen[row - 1].size() < (unsigned)col)
    screen[row - 1].resize(col);

You're only resizing screen[99] here. screen[9] still has size 0 , which is why you can't access screen[9][9] (you could, however, access screen[99][9] ).

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