【发布时间】:2017-10-12 21:25:13
【问题描述】:
我需要编写一个函数,该函数将使用指针在 C 中复制多维数组。我在 Gentoo 上使用 gcc 5.4.0 和 clang 3.9.1。我使用了一个事实,即使用数组的名称与引用它的第一个元素的地址相同,所以如果我们有二维数组,那么array_2d = &array_2d[0] 和*array_2d = *(&array_2d[0]) = array_2d[0]。这是我的代码:
#include <stdio.h>
#define ROWS 2
#define COLS 3
void copy_ptr(double *src, double *dest, int len);
void copy_ptr2d(double **src, double **dest, int rows, int cols);
int main() {
double array[ROWS][COLS] = { { 12.3, 55.1 }, { 33.6, 21.9, 90.8 } };
double array2[ROWS][COLS];
printf("Array { { 12.3, 55.1 }, { 33.6, 21.9, 90.8 } }\n");
printf("Array copy:\n");
copy_ptr2d(array, array2, ROWS, COLS);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("array2[%d][%d]: %lf\n", i, j, array2[i][j]);
}
printf("\n");
}
return 0;
}
void copy_ptr2d(double **src, double **dest, int rows, int cols) {
for (int i = 0; i < rows; i++) {
copy_ptr(*src, *dest, cols);
src++;
dest++;
}
}
void copy_ptr(double *src, double *dest, int len) {
for (int i = 0; i < len; i++) {
*dest = *src;
dest++;
src++;
}
}
gcc 5.4.0下编译代码的结果:
pecan@tux ~ $ gcc main.c
main.c: In function ‘main’:
main.c:13:16: warning: passing argument 1 of ‘copy_ptr2d’ from incompatible pointer type [-Wincompatible-pointer-types]
copy_ptr2d(array, array2, ROWS, COLS);
^
main.c:6:6: note: expected ‘double **’ but argument is of type ‘double (*)[3]’
void copy_ptr2d(double **src, double **dest, int rows, int cols);
^
main.c:13:23: warning: passing argument 2 of ‘copy_ptr2d’ from incompatible pointer type [-Wincompatible-pointer-types]
copy_ptr2d(array, array2, ROWS, COLS);
^
main.c:6:6: note: expected ‘double **’ but argument is of type ‘double (*)[3]’
void copy_ptr2d(double **src, double **dest, int rows, int cols);
^
pecan@tux ~ $ ./a.out
Array { { 12.3, 55.1 }, { 33.6, 21.9, 90.8 } }
Array copy:
Segmentation fault
并且在clang 3.9.1下:
pecan@tux ~ $ clang main.c
main.c:13:16: warning: incompatible pointer types passing 'double [2][3]' to parameter of type 'double **' [-Wincompatible-pointer-types]
copy_ptr2d(array, array2, ROWS, COLS);
^~~~~
main.c:6:26: note: passing argument to parameter 'src' here
void copy_ptr2d(double **src, double **dest, int rows, int cols);
^
main.c:13:23: warning: incompatible pointer types passing 'double [2][3]' to parameter of type 'double **' [-Wincompatible-pointer-types]
copy_ptr2d(array, array2, ROWS, COLS);
^~~~~~
main.c:6:40: note: passing argument to parameter 'dest' here
void copy_ptr2d(double **src, double **dest, int rows, int cols);
^
2 warnings generated.
pecan@tux ~ $ ./a.out
Array { { 12.3, 55.1 }, { 33.6, 21.9, 90.8 } }
Array copy:
Segmentation fault
我不知道为什么我有内存泄漏以及我做错了什么,我得到了“分段错误”。谁能帮帮我?
【问题讨论】:
-
我喜欢这个解决方案 printf("Array { { { 12.3, 55.1 }, { 33.6, 21.9, 90.8 } }\n");但是 ROWS 等于例如 10 呢?:)
-
二维数组不是指向指针的指针。
-
那些警告告诉你一些事情。 double[][] 与 double ** 不同。
-
我投票决定将此问题作为题外话结束,因为 OP 只需要学习基本的东西——至少要了解双精度、整数、指针和数组之间的区别。类似的问题一直在这里被问到。零努力问题(即 OP 没有做任何事情来找到答案)
-
修复this
标签: c arrays pointers multidimensional-array