Median calculator

Hello, I made a program to calculate the median of the numbers you enter, however, I'm using a global pointer. By what I've read in the internet, global variables are "evil", so, does this apply to pointers as well? I tried making this pointer a local pointer, but the program stops functioning. Can anyone help me please? Here's the program 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
//median
#include <iostream>
using namespace std;
int *pointer;

float median (int);

int main () {
	int a;
	int b;
	cout << "Insert how many numbers you want to calculate\n";
	cin >> a;
	pointer = new int[a];
	cout << "\nInsert the numbers\n" << endl;

	for (b=0;b<a;b++) {
		cin >> pointer[b];
		cout << "\n"; 
	}

	cout << "\nThe median of those numbers is: " << median(a)/a;
}

  
float median (int x) {
	if (x>0) {
		x--;
		return (pointer[x] + median(x));
	}
	else {
		return 0;
	}
}
You can pass it as a function argument.
You should clean up your dynamically allocated memory when you're done with it. For a small app like this it doesn't really matter, the OS will clean up the mess you leave behind, but you should develop good cleanup habits now. As your apps grow larger, bad memory allocation habits will start causing you a lot of grief.

Basically, you should have a delete for every new, as well as a delete[] for every new[].
Topic archived. No new replies allowed.