由于 C++ 中的分段错误导致应用程序崩溃的方法

method giving app crashes due to segmentation fault in c++

这种简单的循环方法无法 运行 并且出现错误 “app crashed”。当我在在线编译器中检查它时,它给出了 'segmentation fault(core dumped)'-

string studies(setMatter ch) {
  string a = "LISTEN CAREFULLY!\n";
  int i = 0;
  while (i <= ch.a.quantity()) {
    a += ch.a.getAns(i);
    i++;
  }
  return a;
}

上面代码中的方法参考也见-

class Answer {
 private:
  vector<string> ch;

 public:
  void setAns(string ans) { ch.push_back(ans); }

  string getAns(int num) { return (ch[num]); }

  int quantity() { return ch.size(); }
};

我访问的是非绑定元素吗?但我不知道在哪里,因为我在编程中每个数字都从 0 开始

是的,你是。

while(i<=ch.a.quantity()){

应该是

while(i<ch.a.quantity()){

有效向量索引为零,直到向量大小减一。这应该是显而易见的,如果有效索引从零开始并达到向量的大小,那么有效索引将比向量的大小多一个,这是没有意义的。

这种任务通常使用 for 循环

for (int i = 0; i < ch.a.quantity(); i++) {
    a += ch.a.getAns(i);
}

这样读起来更容易一些。