I am trying to copy one dynamically reserved array into another, both of which are placed in a vector. But it does not work. Why?
struct A {
int *p;
};
int main()
{
vector<A> v;
A test;
test.p = new int[5];
//fill the array
for (int i = 0; i < 5; i++)
test.p[i] = i;
v.push_back(test);
A test2;
test2.p = new int[10];
//fill the array
for (int i = 0; i < 10; i++)
test2.p[i] = i;
delete[] test.p;
//reallocate test to test2
test.p = new int[10];
//copy test2 to test
for (int i = 0; i < 10; i++)
test.p[i] = test2.p[i];
//delete test2
delete[] test2.p;
//print the array
for (int i = 0; i < 10; i++)
cout << v[0].p[i] << endl;
return 0;
}
My output is:
0
0
-997294064
32767
4
0
33
0
-997220688
32767