#include <iostream>
// Function to dynamically allocate and clone a 2D array
int** cloneArray(int arr2D[][4], int rows, int cols) {
int** clone = new int*[rows];
for (int i = 0; i < rows; ++i) {
clone[i] = new int[cols];
for (int j = 0; j < cols; ++j) {
clone[i][j] = arr2D[i][j];
}
}
return clone;
}
// Function to display a dynamically allocated 2D array
void displayDynamicArray(int** arr, int rows, int cols) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
}
// Function to display a fixed size 2D array.
void displayFixedArray(int arr[][4], int rows, int cols){
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
}
int main() {
int arr2D[][4] = { {1, 2, 3, 0}, {4, 5, 6, 85}, {7, 8, 9, 10} };
int rows = sizeof arr2D / sizeof arr2D[0];
int cols = sizeof arr2D[0] / sizeof(int);
std::cout << "Original Array:" << std::endl;
displayFixedArray(arr2D, rows, cols);
// Cloning the array
int** clone = cloneArray(arr2D, rows, cols);
std::cout << "Cloned Array:" << std::endl;
displayDynamicArray(clone, rows, cols);
// Freeing dynamically allocated memory
for (int i = 0; i < rows; ++i) {
delete[] clone[i];
}
delete[] clone;
return 0;
}
/*
run:
Original Array:
1 2 3 0
4 5 6 85
7 8 9 10
Cloned Array:
1 2 3 0
4 5 6 85
7 8 9 10
*/