dynamic memory allocation c++ -


i have following dynamically allocated array

int capacity = 0; int *myarr = new int [capacity]; 

what happens if this:

for (int = 0; < 5; ++i)  myarr[++capacity] = 1; 

can cause error if for loop executed many times more 5? worked fine small numbers, i'm wondering if maybe wrong approach.

you setting memory outside of bounds of array. might overwrite memory being used in part of program, undefined behavior. fix should declare array this:

int* myarray = new int[5];

which make don't allocate out of bounds of array.

however, better use std::vector. prevent situations occurring managing memory itself. can add items std::vector this:

vector.push_back(myitem); 

and can declare vector of ints this:

std::vector<int> vector; 

you can read more std::vector here.