c++ - Trying to dynamically increase array size -
i working on program user keeps entering numbers, saved array, when array full trying copy original array new 1 one , continue fill array cannot work @ all. here code far
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; int main() { int size; cout << "please enter how many numbers want enter: "; cin >> size; double *array = new double*[size]; cout << "please enter numbers: "; for(int = 0; < size; i++) { cin >> array[i]; if(i == size-1) { int newsize = 2*size; double *arrayb = new double*[newsize]; for(int = 0;i<size;i++) { arrayb[i] = array[i]; } delete [] array; array = arrayb; size = newsize; } } }
i can compile making double pointers point @ doubles, instead of arrays of double pointers
int size; cout << "please enter how many numbers want enter: "; cin >> size; double *array = new double[size]; // ^--- not pointers doubles cout << "please enter numbers: "; for(int = 0; < size; i++) { cin >> array[i]; if(i == size-1) { int newsize = 2*size; double *arrayb = new double[newsize]; // ^--- not pointers for(int = 0;i<size;i++) { arrayb[i] = array[i]; } delete [] array; array = arrayb; size = newsize; } }
you have allocated enough memory in first new data. but whn 1 before end of current value of size
double space allocate. , make size = newsize
. outer for
loop never end, unless exception gets thrown, example bad::alloc
bound happen eventually.
Comments
Post a Comment