我希望为C语言中的数据立方体分配内存,也就是说,我需要分配一个三维数组。然而,我的代码却返回“分段错误”,我不知道为什么。
我认为我的循环是正确的,但事实上,我的代码并不能正常工作。
这是我的代码:
我认为我的循环是正确的,但事实上,我的代码并不能正常工作。
这是我的代码:
int malloc3dfloat(float ****array, int q, int r, int s) {
// allocate the q*r*s contiguous items
float *p = (float *) malloc(q*r*s*sizeof(float));
if (!p) return -1;
// allocate the row pointers into the memory
(*array) = (float ***) malloc(q*sizeof(float**));
if (!(*array)) {
free(p);
return -1;
}
for (int i=0; i<q; i++)
{
(*array)[i] = (float **) malloc(r*sizeof(float*));
if (!(*array[i]))
{
free(p);
return -1;
}
}
//set up the pointers into the contiguous memory
for (int i=0; i<q; i++)
{
for (int j=0; j<r; j++)
{
(*array)[i][j] = &(p[(i*r+j)*s]);
}
}
return 0;
}
sizeof
放在最前面。您可能会在乘法运算中溢出int
。如果使用float *p = malloc(sizeof(*p) * q * r * s);
,则乘法运算将在size_t
上执行,这样就不会溢出了。 - alx - recommends codidactmalloc()
的结果进行类型转换,并避免使用sizeof(type)
。详情请参见https://dev59.com/dHRB5IYBdhLWcg3wgHWr#605858。 - alx - recommends codidactif (!(*array[i]))
应该改为if (!((*array)[i]))
。 - H.S.float *p = malloc(q * r * s * sizeof *p);
,然后通过p[(x) + (y * q) + (z * q * r)]
这些坐标访问立方体。最后一个表达式中的括号并不是必须的,但是为了清晰起见加上比较好。 - Cheatah