8 9
|
int i = 0,size = 0, seed, temp;
int array[size];
|
The variable
array is an array of 0 size. Changing the variable
size after the fact will not affect the number of elements your array can hold. You've already dictated its limit. (This is not mentioning how variable-sized static arrays are not allowed
at least until C++14).
You can instead:
- Create excess storage space in the hopes the user does not exceed the limit
- Use dynamic arrays and reallocate when a larger size is needed
- Take advantage of the containers provided by the standard (which manage those dynamic arrays for you)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
//Excess storage space
char stream_buf[80] = {'\0'); //Let's hope 80 is sufficient
//Dynamically sized arrays
int data* = new int[capacity]; //Remember that changing capacity afterward will
// not change the size limit of the array
unsigned size(0);
//...
if(size >= capacity){
//1) Allocate memory for new array that has a larger capacity
//2) Copy data from old array to new array
//3) Free the memory from the old array
//4) Update capacity and size information
}
//Containers ~ std::vector
std::vector<int> data; //0 size
data.push_back(rand()%13+1); //size increased by 1
|
Extra:
If you don't need to store all the numbers, you can use a FILO (First In Last Out) system with a static sized array (with a set size). With this system, each new data point sits at the back (or end) of the array. Whenever the size limit is reached, the oldest data point can be thrown away to make room for the new data point.
If you want to go crazy with different ways to deal with this issue, you can even go for a circular list design, which is like FILO but doesn't involve shifting all the elements.