Hi guys, I'm quite new to C++ and I'm having problems with a simple operation.
I have to resize an array of structs, but seeing as I am having a problem with the concept, i'll post an example with a simple array of integers.
Please bear in mind that this is for an assignment in college, therefore - while using vectors would solve my problem, - I'm not allowed use anything other than simple arrays.
Presume that in main() i have:
int size = 3;
int * a = new int;
a[0] = 1;
a[1] = 2;
a[2] = 3;
i want to write a function to push a new value into the array a. I thought of doing it like this:
void newInt(int value, int * a, int & size){
int newsize = size + 1;
int * temp = new int[newsize];
//move over values to temporary array
for(int i=0; i < size; i++){
temp[i] = a[i];
}
//insert the new value in the temporary array
temp[size] = value;
//free memory in old array
delete [] a;
//get old array to reference the temporary one
a = temp;
//increase the size of a to keep track of changes
size++;
}
well, if i run this it apparently works the first time but if i print out the values contained in a i get something like:
0
2
3
4007152
when i obviously expected
1
2
3
<whatever new value had been passed to newInt()>
Thanks everybody for your help, hope the problem is clear enough.