Sortscore function creating an issue. (pointers)

My Sortscore function is creating an issue with my program where it changes everything to memory values so when I use the average function I no longer get a value I instead get a memory value.

What I'm trying to do with my code is sort the added test scores take the average.

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
float averageScore(int sum, int size);
void Sortscores(int *score, int size);

int main() {
	const int size = 5;
	int testscore[size];
	int *score = testscore;
	float sum=0.0;

	for (int i = 0; i < size; i++) {
		cout << "Please enter a test score #" << i+1 <<  " : ";
		cin >> score[i];
		while (score[i] < 0){
			cout << "Incorrect Test Score!!!" << endl << "Please enter a test score:";
			cin >> score[i];
		}
		
	}

	cout << endl;
	cout << "Your test scores were: ";
	for (int i = 0; i < size; i++) {
		if (i < 4) {
			cout << score[i] << ", ";
		}
		if (i == 4) {
			cout << score[i];
		}

	}

	cout << endl << endl;
	Sortscores(score, size);

	for (int i = 0; i < size; i++) {
		cout << score[i];
	}
	
	cout << endl;

	for (int i = 0; i < size; i++) {
		sum += score[i];
	}


	cout << fixed << showpoint << setprecision(1);
	cout << "Your average score is: "<<  averageScore(sum, size);
	return 0;
}

void Sortscores(int *score, int size) {
	
	int holder = 0;
	for (int i = 0; i < size; i++) {
		if (score[i] > score[i + 1]) {
			holder = score[i + 1];
			score[i + 1] = score[i];
			score[i] = holder;
		}
	}
	
}


float averageScore(int sum, int size) {
	float average;
	

	average = sum / size;

	return average;
}
The problem is that you access memory that doesn't belong to you.
At the end of the loop i = 4
holder = score[i + 1];
So would I fix that by adding a if statement?

such as

1
2
3
4

if (score[4]){
holder= score[i];
}
Last edited on
From the wiki article it seems as though it's better to subract 1 from the index instead of adding one to the index.

That way I won't go past my final value right?

although I don't understand the point of the following section the article references.

end if
end for
n = newn
until n = 0
end procedure

Last edited on
Topic archived. No new replies allowed.