如何在c++中使用calloc为3D数组分配内存
how to allocate memory for 3D array using calloc in c++
我想在c++中为3d数组一个接一个地分配内存,就像…
typedef struct {
int id;int use;
}slotstruct;
slotstruct slot1[3][100][1500]; // This should be 3d array
for(i=0;i<3;i++){
for(j=0;j<100;j++){
for(k=0;k<1500;k++){
slot1[i][j][k] = (slotstruct *)calloc(1,sizeof(slotstruct));
}
}
}
我已经使用了这个代码,但我得到分割错误。
Write
slotstruct ( *slot1 )[100][1500];
slot1 = calloc( 1, 3 * sizeof( *slot1 ) );
或者试试下面的
slotstruct ***slot1;
slot1 = malloc( 3 * sizeof( slotstruct ** ) );
for ( int i = 0; i < 3; i++ )
{
slot1[i] = malloc( 100 * sizeof( slotstruct * ) );
for ( int j = 0; j < 100; j++ )
{
slot1[i][j] = calloc( 1, 1500 * sizeof( slotstruct ) );
}
}
首先计算所需的总内存量,然后首先为主数组和子数组分配内存,如下所示。不会造成分段故障。即使你可以检查地址,他们也是连续的。试试下面的代码,它对我来说很好:
typedef struct
{
int id;
int use;
}slotstruct;
main()
{
int i,j,k;
char row=2 ,col =3, var=3;
//char **a=(char**)malloc(col*sizeof(char*));
slotstruct*** a =(slotstruct***)calloc(col,sizeof(slotstruct*));
for(i=0;i<col;i++)
a[i]=(slotstruct**)calloc(row,sizeof(slotstruct*));
for(i=0;i<col;i++)
for(j=0;j<row;j++)
a[i][j]=(slotstruct*)calloc(var,sizeof(slotstruct*));
int cnt=0;
for( i=0;i<col;i++)
for( j=0;j<row;j++)
{
for(k=0;k<var;k++)
a[i][j][k].id=cnt++;
}
for(i=0;i<col;i++)
for(j=0;j<row;j++)
{
for(k=0;k<var;k++)
printf("%d ",a[i][j][k].id);
printf("%u ",&a[i][j][k]);
printf("n");
}
}
当你写
时,你已经分配了内存slotstruct slot1[3][100][1500]
你的意思是写以下内容吗?
slotstruct ***slot1
相关文章:
- 如何计算 3d 数组中的索引值在内存中的位置?如何计算字符**中的索引值在内存中的位置?
- 我是 c++ 的新手,有没有一种算法可以找到 3d 数组中最接近的 0 的距离?
- 如何用零填充 3D 数组?
- 将长度可变的 C99 静态 3D 数组传递给函数
- C :将矢量重新为3D数组
- 将动态 3D 数组发送到 C++ 中的函数
- C++ 3D 数组到 1D 会导致堆缓冲区溢出
- 初始化const 3D数组成员变量
- 处理3D数组的边缘和角案例的方法
- 将2D数组的实例分配给3D数组中的索引
- 使用 vector 在 c++ 中声明 3D 数组结构
- 为什么C CHAR数据类型3D数组通过参数第一个括号为空白
- 可以使用 std::copy 将 3D 数组复制到矢量
- 我的重载 [] 运算符不适用于伪 3D 数组
- 从 3D 数组转换为 1D 数组失败
- 如何将3D .OBJ对象表示为3D数组
- 如何在C++中定义每个维度具有不同类型的 3D 数组
- CPP 3D 动态创建由单个内存块组成的 3D 数组
- 视觉读取列文本数据并在C++中放入 3D 数组
- 将 3D 数组的索引传递给函数