/* C言語/C++言語で3次元配列を動的に確保&解放するプログラム 「2次元配列を動的に確保&解放するプログラム」の3次元版です。 */ #include <stdio.h> #include <stdlib.h> #ifdef __cplusplus template<typename T>T***AllocCubic(int u,int v,int w) { int i,j; T***a,**b,*c; try { a=(T***)new char[(sizeof*b*(1+v)+sizeof*c*w*v)*u]; } catch (...) { a=0; } if (a) { b=(T**)(a+u); c=(T*)(b+u*v); } else return 0; for (i=0;i<u;i++,b+=v) for (a[i]=b,j=0;j<v;j++,c+=w) b[j]=c; return a; } #define ALLOC_CUBIC(T,U,V,W) AllocCubic<T>(U,V,W) #define FREE(X) delete[]X #else void*AllocCubic(int s,int u,int v,int w) { int i,j,t=s*w; char***a,**b,*c; a=(char***)malloc(((1+v)*sizeof*a+t*v)*u); if (a) { b=(char**)(a+u); c=(char*)(b+u*v); } else return 0; for (i=0;i<u;i++,b+=v) for (a[i]=b,j=0;j<v;j++,c+=t) b[j]=c; return a; } #define ALLOC_CUBIC(T,U,V,W) (T***)AllocCubic(sizeof(T),U,V,W) #define FREE(X) free(X) #endif int main(void) { int u=3,v=6,w=16,i,j,k; double***a=ALLOC_CUBIC(double,u,v,w); for (i=0;i<u;i++) for (j=0;j<v;j++) for (k=0;k<w;k++) a[i][j][k]=i*256+j*16+k; for (i=0;i<u;i++) { for (j=0;j<v;j++) { for (k=0;k<w;k++) printf("%03X ",(int)a[i][j][k]); printf("\n"); } printf("\n"); } FREE(a); return 0; }