2013-08-21 145 views
1

请我在这个问题上停留了半个小时,找不到为什么会出现错误? 问题代码:测试 生命,宇宙和一切为什么此代码显示codechef上的分段错误?

#include<iostream> 

using namespace std; 

int main() 
{ 
    int a[20],i; 
    cin>>a[0]; 

    for(i=1;a[i-1]!=42;i++) 
    { 
     cout<<a[i]<<"\n"; 
     cin>>a[i]; 
    } 

    return(0); 
} 
+0

呃......你在哪里确定你的循环在'i> 19'之前终止,因此对'a [i]'的任何访问都可能出现段错误? – arne

+0

你的意思是我应该增加数组的大小? – user2696751

+0

@ Nbr44,直到一个数字是42,而不是42个元素。仍然... – chris

回答

4

你的代码试图访问不存在的数组元素,这会导致段错误。你应该停止循环数组的索引得到比数组的长度减去1大前:

int a[20]; 

for (i = 1; i < 20 && a[i - 1] != 42; i++) 
{ 
    // ... 
} 
0
从限制问题

除此之外,您的打印元素,而无需初始化它们

//for i = 1, a[i] is uninitialized 
cout<<a[i]<<"\n"; 

在访问一个局部变量(像这样),你很可能会得到垃圾价值。

这可能是更好的替代品为你正在尝试做的事:

int a[20],i; 
for(i=0;i < 20;i++) 
{ 
    cin>>a[i]; 
    if (a[i] == 42) 
     break; 
    cout<<a[i]<<"\n"; 
} 
0

你要打印未初始化的数据...

#include<iostream> 
using namespace std; 
int main() 
{ 
int a[20],i; 
cin>>a[0]; // a[0] uninitialized 
for(i=1;a[i-1]!=42;i++) 
    { 
    cout<<a[i]<<"\n"; 
    cin>>a[i]; 
    } 
return(0); 
} 

在for循环中首先获得数据然后打印它。您的数组大小是20,但您正在尝试写入最多42.

0
  • 您使用数组val在初始化它们之前。 C++不会为你初始化非静态数组,除非你告诉它,所以$ DEITY知道那里有什么。从技术上讲,任何内容都可能导致例外......或其他许多事情。 (对于整数,在x86机器上,这实际上是不太可能的,但在其他地方,这是可能的。)

  • 用户可以输入20个以上的数字。但这只是一个更普遍问题的特例:您允许未知数量的条目,但无法在不崩溃的情况下全部接受它们。

如果事先不知道会有多少物体,请使用矢量。

#include <iostream> 
#include <vector> 

using namespace std; 

int main() 
{ 
    std::vector<int> a; 
    int entry; 
    cin>>entry; 

    // Oh, yeah. This. You really, *really* want to check `cin`. 
    // Otherwise, if the user decided to type "i like cheese", you'd loop 
    // forever getting zeros while cin tried to parse a number. 
    // With the array, that'd typically cause a segfault near instantly. 
    // With a vector, it'll just eat up all your CPU and memory. :P 
    while (cin && entry != 42) { 
     a.push_back(entry); 
     cout << entry << "\n"; 
     cin >> entry; 
    } 

    return 0; 
} 
相关问题