#include <iostream>
// Function to create and return a 2D array
int create2DArray(int rows, int cols) {
// Allocate memory for the array of pointers to rows
int array2D = new int*[rows];
// Allocate memory for each row
for (int i = 0; i < rows; ++i) {
array2D[i] = new int[cols];
}
// Initialize the array elements
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
// You can initialize the elements with values as needed
array2D[i][j] = i * cols + j;
}
}
// Return the 2D array
return array2D;
}
// Function to display a 2D array
void display2DArray(int array2D, int rows, int cols) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cout << array2D[i][j] << " ";
}
std::cout << std::endl;
}
}
// Function to deallocate memory used by the 2D array
void delete2DArray(int array2D, int rows) {
// Deallocate memory for each row
for (int i = 0; i < rows; ++i) {
delete[] array2D[i];
}
// Deallocate memory for the array of pointers to rows
delete[] array2D;
}
int main() {
// Define the dimensions of the 2D array
int rows = 3;
int cols = 4;
// Create a 2D array
int myArray = create2DArray(rows, cols);
// Display the 2D array
display2DArray(myArray, rows, cols);
// Deallocate memory used by the 2D array
delete2DArray(myArray, rows);
return 0;
}