c - 为指向二维数组指针的指针赋值

标签 c arrays memory allocation calloc

我相信我的声明不正确。我有一个 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/

相关文章:

hadoop - yarn 在运行 hive 作业时使用了 100% 的资源

java - 如何解决 ThreadPoolExecutor 程序中的 java.lang.outOfMemoryError?

转换缓冲区以在 OS X 中运行和执行

c - 用宏包装函数调用

c++ - 如何选择/替换矩阵中行/列的所有元素?

arrays - matlab 有没有像 python 中那样的列表理解?

c++ - 在环形网格内创建一个 3x3 框

C++ 分配的指针显示意外行为

c - 目前有没有办法让两个以太网端点发现它们之间有多少个交换机或路由?

c - 使用C找到矩阵中每一列的最大元素?