So I made this little piece of code that asks the user the size of an array and the contents of the array (in order) and makes the array in the dynamic memory (heap?).
void leesgetallen() {
int *n = new int();
cout << " Wat is de lengte van de Array?" << endl;
cin >> *n;
int g;
int *A = new int[*n];
cout << "Geef de getallen van de Array in stijgende volgorde." << endl;
for (int i = 0; i < *n; i++) {
cout << "Geef getal nummer " << i << " :";
cin >> g;
A[i] = g;
}
cout << "Ter controle, dit is de ingegeven Array: ";
for (int *pa = A; pa != A + *n; pa++) {
cout << *pa << " ";
}
}
On its own this works perfectly.
However when I then try to use this array (A) and size of said array (*n), it doesn't recognize A and *n. I don't quite understand how I can use these variables as to my understanding if they are in the dynamic memory they should be global?
The reason I need to access them is because I want to use a different function to calculate the average of an inputted array.
like so.
int gem(int a[], int n) {
int som = 0;
for (int *pa = a; pa != a + n; pa++) {
som += *pa;
}
int gemiddelde = som / n;
cout << "Het gemiddelde van deze array is: " << gemiddelde << endl;
return gemiddelde;
}
void leesgetallen() {
int *n = new int();
cout << " Wat is de lengte van de Array?" << endl;
cin >> *n;
int g;
int *A = new int[*n];
cout << "Geef de getallen van de Array in stijgende volgorde." << endl;
for (int i = 0; i < *n; i++) {
cout << "Geef getal nummer " << i << " :";
cin >> g;
A[i] = g;
}
cout << "Ter controle, dit is de ingegeven Array: ";
for (int *pa = A; pa != A + *n; pa++) {
cout << *pa << " ";
}
}
int main() {
leesgetallen();
gem(A, *n);
delete *n;
delete[] A;
}
Can anyone help me out?
ps: all text is in dutch, but that shouldn't really matter I hope.
new int[*n]
creates new, global (in a sense), unnamed array, and returns pointer to its beginning. That pointer is the only way to access that array. But A
, the variable you store it in, is local to leesgetallen
so can only be accessed from said function. To overcome that, you can define A
and n
in main
, for example, and pass references (or pointers) to these variables into leesgetallen
. (Or, as @lorro suggested, return their values in a tuple)
Also note that n
doesn’t need dynamic allocation as you know for sure it will be exactly one int
for your whole program.