全部。我已经尝试了很多次来解决这个问题,感觉我已经快到了,但是我对我需要多少个“*”感到非常困惑!我有一个函数,它接受包含数据文件的目录字符串、一个 int 和指向两个未初始化的二维数组的指针作为输入。该函数读取数据文件,然后分配内存并相应地填充数组。
我知道这段代码是完全错误的,但想法是:
void main()
{
double **Array1;
int **Array2;
int dimension1;
char DirWork[100], buff[100];
f_ReadData(DirWork, dimension1, &Array1, &Array2);
sprintf(buff,"%lf",Array1[0][0]); // Causes segmentation fault
printf(buff);
}
和
void f_ReadData(char *DirWork, int dimension1, double ***Array1ptr, int ***Array2ptr)
{
int ct, ct2;
double **Array1 = *Array1ptr;
int **Array2 = *Array2ptr;
char FullDirArray1[100], FullDirArray2[100];
FILE *d_Array1, *d_Array2;
sprintf(FullDirArray1,"%s%s,DirWork,"Array1.dat");
sprintf(FullDirArray2,"%s%s,DirWork,"Array2.dat");
d_Array1=fopen(FullDirArray1,"r");
d_Array2=fopen(FullDirArray2,"r");
fscanf(d_Array1,"%d", &dimension1);
Array1 = dmatrix(0,dimension1-1,0,3); // allocates memory to Array1 (dimension1 x 3) elements, using nrutil
Array2 = imatrix(0,dimension1-1,0,3); // allocates memory to Array2 (dimension1 x 3) elements, using nrutil
for(ct=0; ct<dimension1; ct++)
{
for(ct2=0; ct2<3; ct2++)
{
fscanf(d_Array1, "%lf", &Array1[ct][ct2];
fscanf(d_Array2, "%d", &Array2[ct][ct2];
}
}
fclose(d_Array1);
fclose(d_Array2);
}
我在这里错过了错误处理,但我确实有一些错误处理......并不是说它有帮助。当我尝试从主函数访问数组时,出现段错误。
如果有人可以提供帮助,我将非常感激...我看到*星星了!谢谢!
最佳答案
那么星星的数量是正确的。
由于您没有将指针复制回您分配的缓冲区,因此出现了段错误。您仅初始化 f_ReadData:Array1,但需要将此值分配回 *Array1ptr。
关于c - 在 C 中将未初始化的二维数组作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9659430/