copy 2 dimensional array c++
To copy a 2-dimensional array in C++, you can follow these steps:
Declare and initialize the source array that you want to copy. Let's call it
sourceArray
.Determine the dimensions of the source array. Let's say it has
rows
rows andcols
columns.Declare and initialize the destination array where you want to copy the elements. Let's call it
destinationArray
.Use nested loops to iterate over each element of the source array. The outer loop iterates over the rows, and the inner loop iterates over the columns.
Inside the nested loops, assign the value of each element from the source array to the corresponding element in the destination array. You can use the row and column indices to access the elements.
After the nested loops, the destination array will contain a copy of the source array.
Here is an example code snippet that demonstrates the above steps:
#include <iostream>
const int rows = 3;
const int cols = 3;
void copyArray(int sourceArray[][cols], int destinationArray[][cols]) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
destinationArray[i][j] = sourceArray[i][j];
}
}
}
int main() {
int sourceArray[rows][cols] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int destinationArray[rows][cols];
copyArray(sourceArray, destinationArray);
// Print the destination array to verify the copy
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cout << destinationArray[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
In this example, the copyArray
function takes the source array and the destination array as parameters. It uses nested loops to copy each element from the source array to the destination array. Finally, the main
function declares and initializes the source and destination arrays, calls the copyArray
function, and prints the destination array to verify the copy.