我在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;
这会生成数据访问冲突错误并终止程序。
我已经阅读并尝试并得出结论 - 我很愚蠢。 请帮忙!!!
答案 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));
}
}
注意:
malloc()
的返回值。malloc()
是否返回成功和失败。