我相信我的声明不正确。我有一个 2D 数组和一个 3D 数组。我出现了段错误,因为我将值 0 或 NULL
分配给其中一个数组。我知道这是试图将地址 NULL
分配给无效的指针。
也许我需要在分配之前取消引用数组?如果是这样,我该怎么做?如果没有,我需要如何声明数组?
double **WeightIH = calloc(51*20,sizeof(double **));
double ***Input = calloc(51*40, sizeof(double ***));
DeltaWeightIH[i][j] = 0.0 ;
最佳答案
最简单的方法是使用 for 循环。就像下面的例子
int i, j = 0;
int rows = 5;
int cols = 2;
int rows2 = 3; // for 3d array
double **arr2d = (double **)calloc(rows, sizeof(double));
double ***arr3d = (double ***)calloc(rows, sizeof(double));
for (i = 0; i < rows; j++)
{
arr2d[i] = (double *)calloc(cols, sizeof(double));
}
arr2d[1][2] = 0.0; //Or *(*(arr2d+1)+2) = 0.0;
//the same thing for 3d it just need another for loop.
for (i = 0; i < rows; j++)
{
arr3d[i] = (double **)calloc(cols, sizeof(double));
for (j = 0; i < cols; j++)
{
arr3d[i][j] = (double *)calloc(rows2, sizeof(double));
}
}
arr3d[1][2][1] = 0.0; //Or *(*(*(arr2d+1)+2)+1) = 0.0;
关于c - 为指向二维数组指针的指针赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34776498/