I'm not sure what I'm doing wrong. I get a warning when I compile and an error after my program runs.
This is the warning I get:
myList2.cpp: In function ‘int main()’:
myList2.cpp:96: warning: deleting array ‘int score [6]’
And this is what shows after my program runs:
a.out(7023) malloc: *** error for object 0x7fff6bae4bf0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
And this is my code:
#include <string>
#include <iostream>
using namespace std;
double getAverage(int* score, int n)
{
int sum = 0;
int c = 0;
for (c = 0; c < n; c++)
sum += score[c];
double average = double(sum) / n;
return average;
}
int compare(const void* pa, const void* pb)
{
const int& a = *static_cast<const int*>(pa);
const int& b = *static_cast<const int*>(pb);
if (a < b) return -1; // negative if a<b
if (a > b) return 1; // positive if a>b
return 0; // 0 for tie
}
bool hasAScore(int size,int score[])
{
int d;
for (d=0; d < size; d++)
{
if (score[d] >= 90)
{
cout << "At least one 'A' grade is present" << endl;
return true;
}
}
cout << "No A grades present" << endl;
return false;
}
int main()
{
// create empty list
const int MAX_SCORES = 6;
int nScores = 0;
int score[MAX_SCORES];
// user input for amount of scores
int size;
cout << "How many scores? ";
cin >> size;
cin.ignore(1000, 10);
int* scoreOne = new int[size];
// read and save the scores
int i;
int aScore;
for (i = 0; i < size; i++)
{
cout << "Enter the number: ";
cin >> aScore;
cin.ignore(1000, 10);
if (nScores < MAX_SCORES)
score[nScores++] = aScore;
} // for
// find the max and min integers
int max = score[0];
int min = score[0];
int b;
for (b = 1; b < size; b++)
{
if (max < score[b]) max = score[b];
if (min > score[b]) min = score[b];
} // for
qsort(score, nScores, sizeof(int), compare);
// printing the values
for (i = 0; i < size; i++)
cout << score[i] << ' ';
cout << endl;
cout << "Maximum: " << max << endl;
cout << "Minimum: " << min << endl;
cout << "Average = " << getAverage(score,size) << endl;
hasAScore(size,score);
delete [] score;
cout << "Press ENTER to continue..." << endl;
cin.get();
return 0;
}