Dynamic array

Jun 1, 2013 at 11:32am
Write a program that reads an unspecified number of scores and determine how many scores are above or equal to the average and how many scores are below the average. Enter a negative number to signify the end of the input. Assume that the number of scores is 1 to 10.

I dunno how to dynamically allocate the size of array based on user input. Any idea?
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
  #include <iostream>
using namespace std;

int main()
{
	int input;
	int num = 1;
	int *scoreArr;

	cout << "Enter the scores (negative number to end)" << endl;
	for (;;)
	{
		cout << "Score " << num << ":";
		cin >> input;
		if (input == -1)
			break;

		num++;
		scoreArr = new int[num];
		scoreArr[num] = input;
	}

	for (int i = 1; i <= num; i++)
	{
		cout << "Result: " << scoreArr[i] << endl;
	}


	cin.get();
	cin.get();
}
Jun 1, 2013 at 11:38am
by doing this:
1
2
scoreArr = new int[num];
scoreArr[num] = input;

multiple independent blocks of int data get allocated as the for loop iterates and all previous allocations get leaked (their addresses lost).

instead use std::vector.
Jun 1, 2013 at 11:50am
Is that any way to achieve the goal without using std::vector?
Jun 1, 2013 at 11:58am
you can use a linked list and keep creating and adding new nodes till the user enters -1.
Jun 1, 2013 at 12:00pm
can you show me how to do that? Thanks.
Jun 1, 2013 at 12:09pm
Is that any way to achieve the goal without using std::vector?

Yes there is. But essentially you end up re-writing the functionality of the vector.

That is, when the capacity of the array is exceeded, allocate a new, larger array, copy all the data from the old to the new and then delete the old.

To do that efficiently, you'd probably want to avoid having to do that on every iteration, so allocate the array somewhat larger than is required each time, and keep track of both the capacity and amount actually used.
Jun 1, 2013 at 1:11pm
hey, you could use malloc() function
printf("enter the no of scores you wanna enter\n");
scanf("%d",&n);

int* p;
p=(int*)malloc(n+1);

use p pointing to the beginning of the array like usual to hold the user inputs!
http://www.cplusplus.com/reference/cstdlib/malloc/
Jun 1, 2013 at 1:36pm
hey, you could use malloc() function
>malloc()
>C++
Just... Don't

And even if you use it, you will still have problems in authors case: assinging a sentiel terminated sequence of unknown size.
If you really do not want to use vector you can overallocate your array. And when num will becomes equal to the size of your current array, reallocate it into array of bigger size.
Topic archived. No new replies allowed.