A()
is not modifying nums
to point at the new array. Even if it were, it is deleting the new array, so nums
would end up pointing at invalid memory. You need to declare the arr
parameter as a reference, and delete the old array instead of the new array:
void A(int** &arr) { int **resize; resize = new int*[size*2]; for(int i = 0; i < size; i++) resize[i] = new int(*arr[i]); cout << endl; delete[] arr; arr = resize; size *= 2; }
For what you are attempting, I think you have too much indirection. Try removing a level:
#include <iostream> using namespace std; int *nums; int size; void A(int* &arr) { int *resize; resize = new int[size*2]; for(int i = 0; i < size; i++) resize[i] = arr[i]; cout << endl; delete[] arr; arr = resize; size *= 2; } int main() { size = 10; nums = new int[size]; for(int i = 0; i < size; i++) nums[i] = i; for(int i = 0; i < size; i++) cout << nums[i] << endl; A(nums); cout << endl; for(int i = (size / 2); i < size; i++) nums[i] = i; for(int i = 0; i < size; i++) cout << nums[i] << endl; delete[] nums; }
Since you are using C++, you should be using a std::vector
instead of a raw array, then you can eliminate A()
altogether:
#include <iostream> #include <vector> using namespace std; vector<int> nums; int main() { nums.resize(10); for(int i = 0; i < nums.size(); i++) nums[i] = i; for(int i = 0; i < nums.size(); i++) cout << nums[i] << endl; nums.resize(nums.size()*2); cout << endl << endl; for(int i = (nums.size() / 2); i < nums.size(); i++) nums[i] = i; for(int i = 0; i < nums.size(); i++) cout << nums[i] << endl; }