dynamically generating 2d array in cpp
Explanation of Dynamically Generating a 2D Array in C++
Step 1: Allocate Memory for Rows
int rows = 3;
int array2D = new int*[rows];
Step 2: Allocate Memory for Columns in Each Row
int cols = 4;
for (int i = 0; i < rows; i++) {
array2D[i] = new int[cols];
}
Step 3: Initialize the Array
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
array2D[i][j] = 0;
}
}
Step 4: Access and Modify Elements
array2D[1][2] = 5; // Modify element in second row, third column
int value = array2D[2][3]; // Access element in third row, fourth column
Step 5: Deallocate Memory (Don't forget this step)
for (int i = 0; i < rows; i++) {
delete[] array2D[i];
}
delete[] array2D;