我想声明一个二维数组(double** data
)。我想通过地址将其传递给辅助函数;所以我通过&data
了,辅助函数有参数double*** d
。
通过这种方式,我在主函数中用于二维数组的索引不再起作用。
测试代码:
#include <stdio.h>
#include <stdlib.h>
void helperfunction(double*** data, int n, int c) {
printf("\nIn helper function\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < c; j++) {
printf("(%i %i %lf) ", i, j, *data[i][j]);
}
printf("\n");
}
}
int main(int argc, char **argv) {
int n = 4; //number of rows
int c = 4; //number of columns
double count = 0.0;
double** data = malloc(n * sizeof(double*));
for (int i = 0; i < n; i++) {
double* row = malloc(c * sizeof(double));
for (int j = 0; j < c; j++) {
row[j] = count;
count += 1.2;
}
data[i] = row;
}
printf("In main function\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < c; j++) {
printf("(%i %i %lf) ", i, j, data[i][j]);
}
printf("\n");
}
helperfunction(&data, n, c);
return 0;
}
输出:
In main function
(0 0 0.000000) (0 1 1.200000) (0 2 2.400000) (0 3 3.600000)
(1 0 4.800000) (1 1 6.000000) (1 2 7.200000) (1 3 8.400000)
(2 0 9.600000) (2 1 10.800000) (2 2 12.000000) (2 3 13.200000)
(3 0 14.400000) (3 1 15.600000) (3 2 16.800000) (3 3 18.000000)
In helper function
(0 0 0.000000) (0 1 4.800000) (0 2 9.600000) (0 3 14.400000)
Segmentation fault (core dumped)
显然,当我*data[i][j]
在辅助函数中引用地址 () 时,索引出现了问题。这是什么原因造成的?