c - 如何在 C 结构中使用二维数组?

标签 c multidimensional-array struct

我需要创建一个包含二维数组的结构,但数组大小可能会有所不同,因此我无法将其定义为恒定长度。我试图用双指针解决这个问题,结果发现双指针与双数组不同。那我该怎么做呢?

struct GaussianKernel {
   int r;
   double weightSum;
   double **kernel;
};

GaussianKernel initializeKernel2D(jdouble sigma){
   int r = (int) ceil(3 * sigma);
   int kernelLen = 2 * r + 1;
   double G[kernelLen][kernelLen];
   double weightSum = 0;
   double temp;

   for (int y = -r; y <= r; y++)
   {
      for (int x = -r; x <= r; x++)
      {
         temp =  exp(-(pow(x, 2) + pow(y, 2)) / (2 * pow(sigma, 2))) / (2 * PI * pow(sigma, 2));
         G[y + r][x + r] = temp;
         weightSum = weightSum + temp;
      }
   }

   struct GaussianKernel GKernel;
   GKernel.r = r;
   GKernel.kernel = G;
   GKernel.weightSum = weightSum;

   return GKernel;
}

最佳答案

您应该将二维动态数组分配为:

GKernel.kernel = malloc(kernelLen * sizeof(double *));
for(i=0;i<kernelLen;i++)
GKernel.kernel[i] = malloc(kernelLen * sizeof(double));

然后您可以根据程序逻辑将值存储在GKernel.kernel

关于c - 如何在 C 结构中使用二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46209696/

相关文章:

c - 所有节点的id与最后添加的节点id相同

c - 将图像构建时间嵌入代码中

java - 为什么我不能像获取行那样简单地获取一维列数组?

javascript - 动态 JavaScript 变量名称

javascript - Angular 1 : populate table with ng-repeat using a 2-d array from server's json

C:结构声明中允许成员之间的操作吗?

c - 从数据类型推导出格式说明符?

c++ - 将 C 变量传递给 C++ 函数

c - 为什么我的回文检查函数总是对回文返回 false?

c - 带和不带结构名称的 Typedef