Reputation: 1
This program compiles fine, but I can't get it to run. Every time I try to run it I get a "segmentation fault (core dump)". I think it has something to do with allocating the memory or declaring the array. I tried to declare the array with one *, but then it won't compile. How do I fix this?
struct classStats
{
float mean;
float min;
float max;
float median;
char *name;
};
int main ()
{
int i=19;
string line;
classStats class_data;
student **array;
float count;
class_data.max = 100;
class_data.min = 0;
class_data.median = array[10] -> mean;
array = (student**) malloc(i* sizeof(student*));
cin >> line;
for (int j=0; j<i; j++)
{
array[j] = (student*) malloc(sizeof(student));
cin >> array[j] -> first;
cin >> array[j] -> last;
cin >> array[j] -> exam1;
cin >> array[j] -> exam2;
cin >> array[j] -> exam3;
array[j] -> mean = ((array[j]-> exam1 + array[j] -> exam2 + array[j] -> exam3) / 3);
cout << array[j] -> mean;
} // end of for
bubble(array, i);
count = 0;
for (int j=0; j<i; j++)
{
count = count + array[j]->mean;
if(array[j]-> mean < class_data.min)
{
class_data.min = array[j]->mean;
}//end of if
else if(array[j]->mean < class_data.max)
{
class_data.max = array[j]->mean;
} // end of else if
}
class_data.mean = count / i;
cout << line << class_data.mean << class_data.min << class_data.max << class_data.mean;
for (int j=0; j<19; j++)
{
cout << *array[j]->first << *array[j]->last << array[j]->mean << endl;
}
free(array);
return 0;
} // end of main
Upvotes: 0
Views: 1341
Reputation: 107
Right here:
class_data.median = array[10] -> mean;
You are dereferencing a pointer that does not point to an actual location in memory, as you call malloc for the array of pointers, then malloc for each pointer in the array after attempting to dereference array in the aforementioned line of code. Initialize median after initializing each student pointer.
Also, since you're using C++, use the new[]
operator, like:
array = new student*[19];
EDIT: Grammar
Upvotes: 0
Reputation: 439
Please have look at following line in your code
class_data.median = array[10] -> mean;
You are trying to access memory location before you allocate memory to array.
Upvotes: 1