运行我的代码时出现分段错误(核心转储)问题

Segmentation fault (Core dumped) issue when running my code

本文关键字:核心 转储 问题 错误 分段 代码 我的 运行      更新时间:2023-10-16

我正在做的作业,我不知道为什么当我尝试运行我的程序时,它会给出错误"分段错误(核心转储(。已经尝试了一段时间,我看不出我哪里出错了。我研究了分段错误并逐行浏览了我的代码,但我仍然不知道。对于用 c++ 编码来说还是很新的。

//This program reads the last names of the candidates and the number of votes they receive. The
program sorts and outputs the candidates based on votes received in descending order.
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void openFile(ifstream&);
void getData(ifstream&, string [], int [], int &);
void computePercentages(int[], double [], int &);
void sortVotes(string [], int [], double [], int);
int findSmallestIndex(const int[], int, int);
const int SIZE = 30;
int main(){
string name[SIZE];
double percentages[SIZE];
int votes[SIZE];
int size, sum;
ifstream in;
openFile(in);
getData(in, name, votes, size);
computePercentages(votes, percentages, sum);
sortVotes(name, votes, percentages, size);
for(int i = 0; i < size; i++)
cout << name[i] << " " << votes[i] << " " << setprecision(4) << percentages[i] << endl;
in.close();
return (0);

}
void openFile(ifstream& in){
string filename;
cout << "Enter file name: ";
cin >> filename;
in.open(filename.c_str());
}
void getData(ifstream& in, string n[], int v[],int& s){
int x = 0;
for (int s = 0; s < SIZE; s++){
n[s] = x;
v[s] = x;
}
in >> n[s] >> v[s];
while (!in.eof()){
s++;
in >> n[s] >> v[s];
}
}
void computePercentages(int v[], double p[], int& sum){
int total = 0;
for (int i = 0; i < SIZE; i++)
total = total + v[i];
double factor = 100.0 / total;
for(int i = 0; i < SIZE; i++)
p[i] = factor * v[i];
}
void sortVotes(string n[], int v[], double p[],int s){
for(int index = 0; s - 1; index++){
int smallestIndex = findSmallestIndex(v, s, index)
swap (n[index], n[smallestIndex]);
swap (v[index], v[smallestIndex]);
swap (p[index], p[smallestIndex]);
}}
int findSmallestIndex(const int v[], int s, int start){
int smallestIndex = start;
for (int i = start +1; i < s; i++)
if (v[i] < v[smallestIndex])
smallestIndex = i;
return smallestIndex;
}
void swap(string &a, string &b){
string temp = a;
a = b;
b = temp;
}
void swap(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
void swap(double &a, double &b){
double temp = a;
a = b;
b = temp;
}

就像我说的,我不知道我在这里哪里出错了。任何见解都会有所帮助。

在下面的代码中,第一个循环将"s"设置为SIZE,数组长度也是"SIZE"。

void getData(ifstream& in, string n[], int v[],int& s){
int x = 0;
for (int s = 0; s < SIZE; s++){
n[s] = x;
v[s] = x;
}
in >> n[s] >> v[s];
while (!in.eof()){
s++;
in >> n[s] >> v[s];
}
}

第二个循环(while(继续递增"s"(所以现在 s> SIZE(,这会导致在执行in >> n[s] >> v[s];时数组访问无效,因为n[s]v[s]现在访问超过为长度为 SIZE 的数组分配的内存。

另外,由于这是C++,请使用std::arraystd::vector.