malloc'ed 3d数组生成数据访问冲突

时间:2012-01-11 05:30:43

标签: c malloc multidimensional-array

我在C中有一个malloc'ed三维双数组,当通过索引访问时会产生数据访问冲突错误。

分配函数:(简化版本不检查空值或错误时释放)

 #define DIMENSIONA 50
 #define DIMENSIONB 30
 #define DIMENSIONC 2

 double *** Array;

 void InitialiseDataStructure(void)
 {
 int Counter = 0;
 int PointCounter = 0;  

 Array = (double ***)malloc(DIMENSIONA * (sizeof(double**)));   

 for (Counter = 0; Counter < DIMENSIONA; Counter++)
   {               
      Array[Counter] = (double **)malloc(DIMENSIONB * sizeof(double *));                                  

      for (PointCounter = 0; PointCounter < DIMENSIONB; PointCounter++)
      {          
           Array[Counter][PointCounter] = (double *)malloc(DIMENSIONC * sizeof(double));

      }

   }
 }

然后像这样访问数组:

 Array[x][y][z] = 0;

这会生成数据访问冲突错误并终止程序。

我已经阅读并尝试并得出结论 - 我很愚蠢。 请帮忙!!!

1 个答案:

答案 0 :(得分:2)

以下POINTS_PER_GEOFENCE循环中的for是什么?

  for (PointCounter = 0; PointCounter < POINTS_PER_GEOFENCE; PointCounter++)

不应该是

Array = malloc(DIMENSIONA * (sizeof(double**)));   
for (Counter = 0; Counter < DIMENSIONA; Counter++) {               
      Array[Counter] = malloc(DIMENSIONB * sizeof(double *));                                  
      for (PointCounter = 0; PointCounter < DIMENSIONB; PointCounter++) {     
          Array[Counter][PointCounter] = malloc(DIMENSIONC * sizeof(double));
      }
}

注意:

  • 阅读this以了解malloc()的返回值。
  • 在使用之前,您需要检查malloc()是否返回成功和失败。