用cpp实现一维数组的深拷贝实现二维数组深拷贝
时间: 2023-10-17 18:21:00 浏览: 84
深拷贝例.cpp
一维数组的深拷贝:
```cpp
#include <iostream>
using namespace std;
int main()
{
int arr1[] = {1, 2, 3, 4, 5};
int size = sizeof(arr1) / sizeof(int);
int *arr2 = new int[size];
// 深拷贝
for (int i = 0; i < size; i++) {
arr2[i] = arr1[i];
}
// 打印arr2
for (int i = 0; i < size; i++) {
cout << arr2[i] << " ";
}
cout << endl;
// 释放内存
delete [] arr2;
return 0;
}
```
二维数组的深拷贝:
```cpp
#include <iostream>
using namespace std;
int main()
{
int arr1[][3] = {{1, 2, 3}, {4, 5, 6}};
int row = sizeof(arr1) / sizeof(arr1[0]); // 行数
int col = sizeof(arr1[0]) / sizeof(int); // 列数
int **arr2 = new int*[row];
// 分配内存
for (int i = 0; i < row; i++) {
arr2[i] = new int[col];
}
// 深拷贝
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
arr2[i][j] = arr1[i][j];
}
}
// 打印arr2
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << arr2[i][j] << " ";
}
cout << endl;
}
// 释放内存
for (int i = 0; i < row; i++) {
delete [] arr2[i];
}
delete [] arr2;
return 0;
}
```
阅读全文