c++ - 阵列分段故障

标签 c++ arrays segmentation-fault fstream

我遇到了段错误的问题。 看:

#include<fstream>
using namespace std;
int main(){
    int n,i,vector[10001],vectorcopy[10001];
    ifstream in("program.in");
    ofstream out("program.out");
    in>>n;
    for(i=1;i<=n;i++){
        in>>vector[i];
        vectorcopy[i]=vector[i];
    }
    return 0;}

调试器说: 程序接收信号SIGSEGV,Segmentation fault

请告诉我该怎么做!

最佳答案

如果输入文件 program.in 正确,您的程序(大部分)工作正常。我想您的段错误是由以下原因引起的:

  • 输入错误
  • 程序中缺少输入检查

我在这个 program.in 输入文件中没有发现任何错误:

10
1
2
3
4
5
6
7
8
9
10

其他错误

我说“大部分”是因为您的程序中还有一些其他错误。它们现在不会造成麻烦(C++ 称之为“未定义行为”),但迟早它们会:

  • 对于大小为 n 的数组,索引从 0 开始到 n - 1 结束;使用数组时,不要这样写 for 语句:

    for (i = 1; i <= n; i++)
    

只需将其重写为:

    for (i = 0; i < n; i++)
  • 你没有使用vectorcopy数组
  • 您没有向program.out 输出文件写入任何内容

关于c++ - 阵列分段故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13540580/

相关文章:

c++ - "there is no smaller array object that satisfies these constraints"是什么意思?

c++ - 如何列出 mac os 中动态库中包含的函数/符号?

统计评论字符数的C程序

c - 访问二维结构数组上的值

c++ - "Out of bound iterator"为空集

c++ - "template<class C> void mini(C &a4, C b4) { a4 = min(a4, b4); }"定义是什么意思?

c++ - 我可以使用 std::unique_ptr<BaseClass>(&DerivedClass) 吗?

c - 如何解决此错误 : segmentation fault?

java - 解释代码(带有数组的 if 语句)

C++ - 递归函数中的字符串流