多次元配列の動的確保:プログラム覚え書き

C言語プログラム覚え書き1回目
まずは画像処理で頻繁に使う2次元メモリの動的確保

unsigned char **image; //ポインタのポインタで宣言
int hight=480;     //画像の縦幅
int width=640;     //画像の横幅

//メモリの確保
image=(unsigned char **)calloc(hight,sizeof(unsigned char*));
for(int y=0;y<hight;y++) image[y]=(unsigned char *)calloc(width,sizeof(unsigned char));	

for(int y=0;y<hight;y++){
 for(int x=0;x<width;x++){
  image[y][x]=100;  //ここに画像処理を書く
 }
}

//メモリの解放
for(int y=0;y<hight;y++) free(image[y]);
free(image);


これを応用すれば何次元でも確保できるはず

int ***array;
int size1=10;
int size2=20;
int size3=30;

array=(int ***)calloc(size1,sizeof(int**));
for(int x=0;x<size1;x++) array[x]=(int **)calloc(size2,sizeof(int *));
for(int x=0;x<size1;x++){
 for(int y=0;y<size2;y++) array[x][y]=(int *)calloc(size3,sizeof(int));
}

アクセスするときはarray[x][y][z]