简体   繁体   English

调整向量大小时出现运行时错误

[英]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: cout不打印任何内容,并且出现此错误:

Segmentation Fault (core dumped)

In linux. 在Linux中。 Is anything wrong in the program? 程序有什么问题吗?

If col and row have lower numbers there's no problem. 如果colrow数字较小,则没有问题。

You're resizing screen to row elements, but then you access element row in it. 您正在将screen大小调整为row元素,但随后访问其中的元素row vector s in C++ are, like arrays, 0-based, so valid indexes are 0...row-1 . 与数组一样,C ++中的vector都是基于0的,因此有效索引为0...row-1

Same goes for the inner vectors and col . 内部向量和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[99]大小screen[99] screen[9] still has size 0 , which is why you can't access screen[9][9] (you could, however, access screen[99][9] ). screen[9]大小仍然为0 ,这就是为什么您无法访问screen[9][9] (但是,您可以访问screen[99][9] )的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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