2021年2月5日星期五

Segmentation fault when using C++ array in for loop

I am trying to write a C++ code to sort numbers from an input file into two arrays, one even and one odd. I am having a few related issues with this code. Firstly if I remove the line cout << "even " << evenArray[nEven] << endl; or cout << "odd " << oddArray[nOdd] << endl; then I get exited, segmentation fault. If I do include these lines then the code will run as expected printing every number and the associated array. However, there are always a few numbers in the code that print as either even 6299840 or odd 0 (for a line that is not 0, lines that are 0 correctly sort as even) When I print the variable number it prints correctly but when I print evenArray[nEven] the error occurs. Finally, cout << oddArray[0] << endl << evenArray[0]; prints both even and odd as 17. While this is correct for odd, it is not for even. Both arrays print the same values in the correct order for the odd array from index 0-3. At index 4 odd prints the next in the sequence and even prints 6299840. I am using Repl to run this code.

#include <iostream>  #include <fstream>  #include <iomanip>  #include <string>  using namespace std;  int main() {      ifstream inFile;   int nEven = 0, nOdd = 0;  int number;  int evenArray[nEven]  int oddArray[nOdd];  inFile.open("input.txt");  if (!inFile)     cout << "Cannot open file, terminating program"<< endl;  else  {    while(!inFile.eof() && inFile >> number) {        if (number % 2 == 0) {          evenArray[nEven] = number;          cout << "even " << evenArray[nEven] << endl;          nEven += 1;          sumEven += number;        }        else {          oddArray[nOdd] = number;          cout << "odd " << oddArray[nOdd] <<endl;          nOdd += 1;          sumOdd += number;        } //end else    } //end of while  inFile.close();  cout << oddArray[0] << endl << evenArray[0];    return 0;  }//end of main   

Here is the data I am using.

46 30 82 90 56 17 95 16 48 26  4 58 0 78 92 60 12 21 63 47  19 41 90 85 14 -9 52 71 79 16  80 51 95 102 34 10 79 95 61 92  89 88 66 18 6 63 66 64 39 5  

This is the output:

46  even 46  30  even 30  82  even 82  90  even 90  56  even 56  17  odd 17  95  odd 95  16  even 16  48  even 48  26  even 26  4   even 4  58  even 58  0   even 0  78  even 78  92  even 92  60  even 60  12  even 12  21  odd 21  63  odd 63  47  odd 47  19  odd 19  41  odd 41  90  even 90  85  odd 85  14  even 14  -9  odd -9  52  even 52  71  odd 71  79  odd 79  16  even 16  80  even 80  51  odd 51  95  odd 6299840  102 even 102  34  even 34  10  even 6299840  79  odd 0  95  odd 95  61  odd 61  92  even 0  89  odd 89  88  even 88  66  even 66  18  even 18  6   even 6  63  odd 63  66  even 66  64  even 64  39  odd 39  5   odd 5  17  17  
https://stackoverflow.com/questions/66073449/segmentation-fault-when-using-c-array-in-for-loop February 06, 2021 at 12:01PM

没有评论:

发表评论