【问题标题】:I get the error which i cant fix : terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted (core dumped)我得到了我无法修复的错误:在抛出“std::bad_alloc”what() 的实例后调用终止:std::bad_alloc Aborted (core dumped)
【发布时间】:2018-03-18 02:30:38
【问题描述】:

我使用了 2D 动态数组,但我不知道如何修复错误,请帮助我!我想从用户那里得到一个字符串并将其分离为一些字符串并将它们放入二维动态数组中。 它是我分配数组的代码部分。

    int colCount,rowCount;
    string** table = new string*[rowCount];
    for(int i = 0; i < rowCount; ++i)
    {
    table[i] = new string[colCount];
    }

【问题讨论】:

标签: c++ arrays memory-management dynamic-memory-allocation bad-alloc


【解决方案1】:

您的代码没有初始化colCountrowCount,因此它们的值是垃圾。您尝试使用未初始化的变量动态分配内存,这当然会调用 Undefined Behavior

初始化你的变量,比如:

int colCount = 5, rowCount = 5;

PS:由于这是C++,我建议你使用std::vector作为二维数组,例如:

std::vector<std::vector<std::string>> table;

【讨论】:

  • 我希望类型为 string ,我可以使用字符串的 2D 向量来模拟 kind 数据库吗?
  • 2D 向量给你一个矩阵@shirazy,其中table[i][j] 是一个字符串。所以是的!
  • 对不起,我不明白。我想要一个二维的字符串向量,这可能吗?像这样的 vector > 或者使用 2D 动态数组会更好?
  • @shirazy 是的,对不起!检查我的更新答案,如果有帮助,请接受! =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-11
  • 1970-01-01
  • 2021-01-14
  • 2020-11-03
相关资源
最近更新 更多