【问题标题】:Getting a segfault working with arrays in C++在 C++ 中使用数组获取段错误
【发布时间】:2015-04-13 01:56:44
【问题描述】:

我正在上一个介绍性 C++ 课程,所以我对此完全陌生,但我似乎在运行时遇到了以下代码的段错误(精简到我认为问题所在的位置):

int main(int argc, char *argv[])
{
string filename;
ifstream infile;
float average;
int const ARRAY_SIZE = 20;
int count = 0;
string responses[ARRAY_SIZE];
string response;
char grade;

welcome();
splash();

cout << showpoint << setprecision(1) << fixed;

cout << "\n\n\n\n\n\n\n\n\n\n\n"
     << "\t\tEnter 8-Ball response file name: ";
cin  >> filename;

infile.open(filename.c_str());
system("CLS");
        cout << "score";
cout << "\n\n\n\n";

if (infile)
    {
        while (!infile.eof())
        {
            infile >> response;
            if (1==1)
            {
                responses[count] = response;
                count ++;
            }

        }
            infile.close();
    }

cout << "\n\n\n";

system("PAUSE");
return 0;
}

那里有一些额外的行、变量等,只是因为这些是从各种旧程序中拼凑起来的,而我没有包含这些函数,因为这似乎不是问题所在。基本上,每当我输入文件名时,都会出现段错误。它打印“分数”,所以在那之后,我尝试取出 if 部分,但它仍然让我感到悲痛,所以看起来问题出在 while 语句中的代码上。 我们还没有详细讨论段错误,所以我什至不知道从哪里开始搜索问题。

【问题讨论】:

  • while (!infile.eof()) 错了,应该是while (infile &gt;&gt; response)。如果您的文件包含超过 20 个响应会怎样?您应该使用std::vector&lt;std::string&gt;,而不是将数组硬编码为任意大小,它会根据需要扩展大小。如果这是你在课堂上所教的,恐怕这是一堂非常糟糕的课。
  • 您是否使用过调试器来单步执行您的程序,以便查看错误发生的位置?段错误通常来自滥用指针或写入数组边界之外。
  • @neil-kirk 是的,这就是我们被教导的内容。这位老师在很多事情上都有些古怪,所以我不能说听到我们以错误的方式学习事情时我感到非常震惊。幸运的是,只剩下几个星期了。看起来你提出的第一个建议主要是直接替代,但我到底该怎么处理第二个?
  • Aha Steephen 打败了我。他展示了如何使用向量。如果您的编译器不支持,您也可以使用 push_back 而不是 emplace_back。您不再需要保留计数变量,因为您可以使用responses.size() 来获取数字。

标签: c++ arrays string segmentation-fault


【解决方案1】:

您对数组大小进行了硬编码,它是否有可能超过该限制?

因此,如果您的响应可以动态增长,请按如下方式声明一个向量

#include<vector> std::vector<std::string> responses;

并按如下方式更正您的循环:

   while (infile >> response;)
    {         
         responses.emplace_back(response);
         count ++;       

    }
     infile.close();

【讨论】:

  • 谢谢你。我应该把“std ...”与我的其他变量对齐吗?它给了我error: ‘vector’ is not a member of ‘std’ 编辑:哦,在这种情况下,响应的数量是,实际上是硬编码的。绝对应该早点提到。
  • 如果你使用的是 using namespace std;我已经假设了,你不需要。但是使用 std::string 比使用命名空间 std; 更好
  • 要解决这个错误,你应该添加#include I added into answer
  • @sagev9000 如果对您有帮助,请采纳!!
猜你喜欢
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多