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:
//median
#include <iostream>
usingnamespace 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 = newint[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 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[].