c - C语言中的内存分配——3D数组
问题描述
我想为 C 语言中的数据立方体分配内存。我的意思是,我需要分配一个 3D 数组。但是,我的代码返回了分段错误,我不知道为什么。
我相信我的循环是正确的,但事实是,我的代码不起作用。
这是我的代码:
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;
}
解决方案
只需将可变长度数组与动态存储一起使用。
float (*array)[r][s]=calloc(q, sizeof *array);
就这样!
现在使用array[i][j][k]
语法来访问单个元素。
推荐阅读
- c# - 如何在仅按一个后停用 Vuforia 中的所有虚拟按钮?
- swift5 - 在 UIStepper 类中存储值
- python - 绑定到扇出的队列的消息数
- android - 将一个简单的 android 应用程序项目迁移到 AndroidX 时,在项目中找不到任何用法?
- asp.net-core-mvc - 在 MVC EF Core 中从 DbContext 创建具有其他对象属性的对象
- c++ - 什么是满足 SOLID 原则的好 C++98 类回调机制?
- c# - 发送到统一 webGl 的实时值
- swift - UIRefreshControl's tintColor can't be initially set
- html - 占位符在 Textarea 中不可见
- c# - 软删除的子对象出现在父对象列表中