Segmentation fault?

Every time I try to run this it just says segmentation fault and i'm not really sure what that is or how to fix it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
  #include <iostream>
#include <iomanip>
using namespace std;

struct StuInfo
{
	int stu_total, stu_possible;
	string name;
};

int main ()
{
	int students, index;
	StuInfo student[students];
	
	
	cout << "How many students grades would you like to calculate?\n";
	cin >> students; 
	
	for (index = 0; index < students; index++)
	{
		cout << "What is the students name?:";
		cin >> student[index].name;
		cout << "Total points earned by student:";
		cin >> student[index].stu_total;
		cout << "Total possible points:";
		cin >> student[index].stu_possible;
	}
	
	cout << "Here is the grade of each student:\n";
	cout << fixed << showpoint << setprecision(2);
	for (index = 0; index < students; index++)
	{
			double grade;
			grade = student[index].stu_total / student[index].stu_possible;
			cout << student[index].name << ":" << grade << "%" << endl;
	}
	return 0;
	}
	
1
2
int students;
StuInfo student[students]; // how many are there? 
Segfaults usually happen when you try to illegally access memory.

Here, it's because your student array is an undefined size, since the students variable is junk when you create the array. You could be accessing an out-of-bounds element in the loop. Could be is the phrase to watch out for here; you have undetermined behaviour and that's not good. :-S

If you don't know the size of your array until runtime, your best bet is to use a std::vector. You can dynamically allocate arrays but it's not a great solution.
Last edited on
Topic archived. No new replies allowed.