malloc(array[][][]), two methods

K. A. Dahlke eklhad at ihnet.UUCP
Sat Sep 8 04:41:13 AEST 1984


I once had to malloc() a 3-dimensional table.
The code was not proprietary, so here is a fragment.

mktbl(){
unsigned short (*freq)[ASIZE][ASIZE];

/* malloc a 3-dimensional table of triple frequencies */
freq = (unsigned short ***)
malloc(sizeof(unsigned short)*ASIZE*ASIZE*ASIZE);
for(i=0;i<ASIZE*ASIZE*ASIZE;++i)
freq[0][0][i]=0;
...
++freq[c1][c2][c3];
...
}

When I asked a structured programmer how to solve this malloc problem,
the answer was immediate and predictable.
"put the array in a structure."
struct FOO {
unsigned short freq[ASIZE][ASIZE][ASIZE];
} *foo;
mktbl(){
/* malloc a 3-dimensional table of triple frequencies */
foo = (struct FOO*)
malloc(sizeof(unsigned short)*ASIZE*ASIZE*ASIZE);
for(i=0;i<ASIZE*ASIZE*ASIZE;++i)
foo->freq[0][0][i]=0;
...
++(foo->freq[c1][c2][c3]);
...
}

The foo-> stuff is annoying to type,
but the structures are simpler to understand, and more portable.
-- 

Karl Dahlke    ihnp4!ihnet!eklhad



More information about the Comp.lang.c mailing list