Segmentation Fault

Hey. I'm learning c++ and I'm doing a program that requires I make multiple user defined functions. At this point I'm working with my first function where I have to make a 2d array, but I keep getting a segmentation fault (core dumped) message. Here is the code:



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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <iomanip>
#include "boost/multi_array.hpp"

using namespace std;

double getGrades (int);
  
void printGrades (int);
  
char moreData (char);


const int tests = 4;

int main ()
{
   double grades;   
   int students;
   char continyou = 'y';
      
      while ( toupper(continyou) == 'Y')
	  
	  {
	      
	    cout << "Enter the number of student who took the tests" << endl;
	    cin >> students;
	    grades = getGrades(students);
	    printGrades(students);
	    continyou = moreData(continyou);
	
	  }
   
   return 0;
   
}
    
double getGrades(int)
      
    {
	int count1, count;
	int students;
	int array1[students][tests];

	
	for(count1 = 0; count1 < students; count1++);
	{
	     for(count = 0; count < tests; count++);
	     {
	       cout << "Enter student " << count1 << "test score for test " << count << ":" << endl;
	       cin >> array1[students][count];
	     }
	}
	return 0;
    }


I feel like I'm waay off. Can someone explain to me why I'm getting my segmentation fault?
You're getting the seg fault probably because in getGrades(), you only specify an int for the parameter, it should be:

double getGrades( int students )

You should be passing in the value that the user typed in the main function. Since students is not initialized in getGrades, the value of students is probably some wacky value or even negative! So, in the getGrades function, take out int students under int count1, count;

Anywhere you have a stack variable, you should initialize it. Even though in the getGrades function you initialize count1 and count in your "for" loops, you should get into the habit of initializing variables when you declare them.
thanks, that fixed the problem and got me a ways further. Now I just have a question. In my second for loop, I want to set it so I calculate an average for each student and finally a class average. How could I do that?
In your getGrades function you have collected all the information that is needed. You will need another function that:

1
2
3
4
5
6
7
8
9
10
    for each student:
        sum up each test (Hint: Another loop)

        this student's average = sum / tests

        add this student's average to the class average

    class average = class average / tests

    


I hope this gives you some ideas!
 
char continyou = 'y';

^ clever xD

still you should probably just make it something like indicator so its not confusing
Last edited on
Topic archived. No new replies allowed.