Help with dynamic array

Hello everyone. Having issues figuring out how to use this dynamic array. The program is just supposed to gather some info into a dynamically allocated array, and then find the average, mean, median, and mode. I can't seem to figure out how to use the array in my function definitions because it's not declared before main. When I define the array before main, I get fatal error LNK1120: 1 unresolved externals. If I take it out I get undeclared identifier. Any help would be GREAT.

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


#include <iostream>
using namespace std;


int numStudents[];

void average(int);


int main()
{
	int *numStudents = NULL; int x, howmany;

	cin >> x;
	numStudents = new int[x];

	for (int i = 0; i < x; i++) //initialize all array elements to 0
		numStudents[x] = 0;
	
	for (int q = 0; q < x; q++)
	{
		cout << "\nEnter the number of movies watched for student " << q + 1 << endl;
		cin >> howmany;
		numStudents[q] = howmany;
	}

	cout << endl << endl;
	
	return 0;
}

void average(int z)
{
	int sum = 0;
	double avg;

	for (int x = 0; x < z; x++) //find average

		sum = sum + *(numStudents + x);

	avg = sum / z;
	cout << "The average is " << avg << endl;

}
Why do you declare

int numStudents[];

at line 7?

As far as I know , it should declare like

int *numStudents;

you can't declare an array without size except for function argument.

And you should delete

*numStudent=NULL

at line 14

In different function scope , the program will use the nearest(scope) variables if it has the same name as others.

So the program will use the numStudents at line 14 , not 7.

and your average function will access line 7 , not 14;

so it doesn't work.
I added line 7 because when it wasn't there, I was getting "undeclared identifier" as the error in my average() function definition. So it seems like youi are saying I should just replace line 7 with line 14.
And that indeed complied, THANK YOU!!!
yeap , that's right.

The code will be like this

int *numStudents; //line 7

int x, howmany; // line 14

and you'll invoke average(x); // line 28

but there is still problem at line 43.

avg = sum / z;

when you calculate the number , the operation will use their own pattern , so the divided will return Integer always.

you should write like

avg = (double)sum / z; // we 'll convert sum to double , and the calculate will use double pattern for calculation . (because double's priority is bigger than integer)
Last edited on
Awesome, thanks a ton for your help. Now I can finish this program.
You're welcome.
you can try to pass that dynamic array to function , not to operate global definition.
so the function declaration is like

void average(int *nums, int x)

After using dynamic memories you should free it .

Find the syntax of delete from books
delete[] dynamicArray;
delete dynamicVar;
Last edited on
Topic archived. No new replies allowed.