【发布时间】:2015-04-23 14:28:48
【问题描述】:
如何在 C 中分配和声明 3D 结构数组? 您是先分配数组还是声明它? 我觉得你必须先分配它,这样你才能声明它,让它在堆上,但是你如何分配尚未制作的东西呢? 另外,您应该一次性分配还是逐个分配? 我是否也将结构正确放入数组中? 我对如何做到这一点的猜测是:
header.h
struct myStruct{
int a;
int b;
};
typedef struct myStruct myStruct_t;
main.c
#include "header.h"
#include <stdio.h>
#include <stdlib.h>
int main(void){
int length=2;
int height=3;
int width =4;
myStruct_t *elements;
struct myStruct arr = (*myStruct_t) calloc(length*height*width, sizeof(myStruct);
//zero based array
arr[length-1][height-1][width-1];
int x=0;
while(x<length){
int y=0;
while(y<height){
int z=0;
while(z<depth){
arr[x][y][z].a=rand();
arr[x][y][z].b=rand();
z++;
}
y++;
}
x++;
}
return 0;
}
【问题讨论】:
-
关于使用
.h和.c文件的题外话:stackoverflow.com/q/3482948/2186301
标签: c arrays struct typedef allocation