Dinamic 2D arrays and resizing | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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; } }

7th Feb 2019, 12:38 AM
Josh
Josh - avatar
2 Answers
+ 5
If you need to resize or grow an array, then perhaps it would be a better idea to use vectors. The idea I've adapted to for using arrays is that the size is fixed and neither the program nor the programmer has to handle such issues. https://www.sololearn.com/learn/261/?ref=app However, if you wish to proceed with the code you have, the idea is to copy the contents of the old dynamic array, to the new dynamic array, delete the old dynamic array, and return the new dynamic array. int** resize(int** arr_old, int new_row, int new_col) { // create int** arr_new using parameters new_row and new_col // copy existing content of arr_old to arr_new // delete arr_old // return arr_new }
7th Feb 2019, 4:05 AM
Hatsy Rei
Hatsy Rei - avatar
0
A.. And of course, I think it would be suitable to post this code written by Bennett Post here, although I have no idea how it works. Sorry to bother, but perhaps you have a word or two (or a better way to go about) pertaining the topic of this thread, Bennett? https://code.sololearn.com/c2273F4lb0Mw/?ref=app
7th Feb 2019, 5:23 AM
Hatsy Rei
Hatsy Rei - avatar