#include <iostream>
// Function to clone a dynamically allocated 2D array (using raw pointers)
template <typename T>
T** clone2DArray(T** arr2D, int rows, int cols) {
if (arr2D == nullptr || rows <= 0 || cols <= 0) {
return nullptr; // Handle invalid input
}
T** cloned = new T*[rows];
for (int i = 0; i < rows; ++i) {
cloned[i] = new T[cols];
for (int j = 0; j < cols; ++j) {
cloned[i][j] = arr2D[i][j];
}
}
return cloned;
}
// Function to delete a dynamically allocated 2D array
template <typename T>
void delete2DArray(T** arr, int rows) {
if (arr == nullptr) return;
for (int i = 0; i < rows; ++i) {
delete[] arr[i];
}
delete[] arr;
}
int main() {
// Dynamically allocated 2D array (raw pointers)
int rows = 3;
int cols = 4;
int** arr2D = new int*[rows];
for (int i = 0; i < rows; ++i) {
arr2D[i] = new int[cols];
for(int j = 0; j < cols; ++j){
arr2D[i][j] = i * cols + j + 1;
}
}
int** clonedArray = clone2DArray(arr2D, rows, cols);
std::cout << "Original Array:" << std::endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cout << arr2D[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << "Cloned Array:" << std::endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cout << clonedArray[i][j] << " ";
}
std::cout << std::endl;
}
// Delete the dynamically allocated arrays
delete2DArray(arr2D, rows);
delete2DArray(clonedArray, rows);
}
/*
run:
Original Array:
1 2 3 4
5 6 7 8
9 10 11 12
Cloned Array:
1 2 3 4
5 6 7 8
9 10 11 12
*/