用一维数组的深拷贝实现二维数组深拷贝,使用c++
时间: 2023-10-17 15:07:53 浏览: 123
下面是一段C语言代码,使用一维数组的深拷贝实现了二维数组的深拷贝:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
int rows = 3;
int cols = 4;
int** arr2d = (int**)malloc(rows * sizeof(int*));
for (int i = 0; i < rows; i++) {
arr2d[i] = (int*)malloc(cols * sizeof(int));
for (int j = 0; j < cols; j++) {
arr2d[i][j] = i * cols + j;
}
}
int* arr1d = (int*)malloc(rows * cols * sizeof(int));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr1d[i * cols + j] = arr2d[i][j];
}
}
int** arr2d_copy = (int**)malloc(rows * sizeof(int*));
for (int i = 0; i < rows; i++) {
arr2d_copy[i] = (int*)malloc(cols * sizeof(int));
for (int j = 0; j < cols; j++) {
arr2d_copy[i][j] = arr1d[i * cols + j];
}
}
printf("original 2d array:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", arr2d[i][j]);
}
printf("\n");
}
printf("copied 2d array:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", arr2d_copy[i][j]);
}
printf("\n");
}
// free memory
for (int i = 0; i < rows; i++) {
free(arr2d[i]);
free(arr2d_copy[i]);
}
free(arr2d);
free(arr2d_copy);
free(arr1d);
return 0;
}
```
这段代码首先创建一个二维数组`arr2d`,然后使用嵌套的for循环对其进行初始化。接下来,创建一个一维数组`arr1d`,使用另一个嵌套的for循环将`arr2d`的元素复制到`arr1d`中。最后,再创建一个二维数组`arr2d_copy`,并使用嵌套的for循环将`arr1d`的元素复制到其中。这样就完成了二维数组的深拷贝。
需要注意的是,这里使用了动态内存分配函数`malloc`来分配数组的内存空间,在使用完毕后需要使用`free`函数释放这些内存空间,以免出现内存泄漏的问题。
阅读全文
相关推荐


















