array size = declared int variable?

Is it possible to make an array size change with a int variable?

Say: I have a program that wants minimum 2 inputs, but offers an option to continue to add another input, endlessly.
These inputs are grades that need to go to another function to calculate their average.

I basically want to be able to expand, transfer, and calc average of an array.


this is the idea, though i know its completely the wrong way to do it... thats what i'd like to do.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
double avg(double);

int main ()
{
	int n = 1;
	double grades[n];
	double course[n];
	cout << "Enter student course:";
	cin << course[n];
	cout << "Enter Student grade:";
        cint << grades[n]

//loop, ask if they want to enter another, if so then n++ or n = n + 1, 
//once answer is n/no then call avg func
  avg (grades[n])

	return 0;
}
]
Last edited on
You can use a variable to declare an array, but you can't change it's size after it is created. You need to use a vector for that. Also, your code will crash on the first cin statement because course[n] is out of bounds.
You need to use a vector for that.

Actually, you CAN dynamically allocate an array, like this:
1
2
3
4
5
6
7
8
9
10
11
int n = 5;
double *grades = new double[n];
double *course = new double[n];

// Use your arrays here, and when you are finished:

delete[] grades;      // Release the memory
grades = 0;           // Reset the pointer

delete[] course;
course = 0;
Last edited on
you gotta create a new array and copy the old one into new one. something like this

1
2
3
4
5
6
7
void extendarray(double *&array, int size, int newSize)
{
        double *temp=new double[newSize];
        for (int i=0; i<size; temp[i]=array[i++]);
        delete [] array;
        array=temp;
}
Topic archived. No new replies allowed.