我在C中有一个malloc’ed的替身三维数组,当通过索引访问时,它会生成数据访问违规错误。
分配功能:(简化版本不检查null或错误时释放)
#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;
这将生成数据访问违规错误并终止程序。
我读了一遍,试着得出结论——我很笨。请帮忙!!!
以下for
循环中的POINTS_PER_GEOFENCE
是什么?
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()
是否返回了成功和失败