Dinamic 2D arrays and resizing | Sololearn: Learn to code for FREE!

0

Dinamic 2D arrays and resizing

is it possible to resize a dinamic 2D array? the main problem is that the 2D array gets re-allocated and the data gets lost, so whats the best solution for keeping the data of original 2d array? here is the example: #include<iostream> using namespace std; void print2dArr(int **arr, int row, int col); int main() { int **arr=nullptr, row, col; cout << "enter size of 2D array row*col " << endl; cin >> row >> col; arr = new int*[row]; for (int i = 0; i < row; i++) { arr[i] = new int[col]; } for (int j = 0; j < row; j++) { cout << "enter values for row " << j + 1 << endl; for (int k = 0; k < col; k++) { cin >> arr[j][k]; } } print2dArr(arr, row, col); // increasing the size of the dinamic array int newCol; cout << "enter the amount of new col for the array: " << endl; cin >> newCol; //.....repeate the above //(could all have been made in a function) arr = new int*[row]; for (int i = 0; i < row; i++) { arr[i] = new int[col+newCol]; } for (int j = 0; j < row; j++) { cout << "enter values for the new col " << endl; for (int k = col; k < col+newCol; k++) { cin >> arr[j][k]; } } //here I get the original cells of array printed with garbage print2dArr(arr, row, col+newCol); for (int l = 0; l < row; l++) { delete[]arr[l]; } delete[]arr; return 0; } void print2dArr(int **arr, int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { cout << arr[i][j] << "\t"; } cout << endl; } }

2/7/2019 12:38:16 AM

Josh