Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!gauss.rutgers.edu!math.rutgers.edu!bumby From: bumby@math.rutgers.edu (Richard Bumby) Newsgroups: comp.lang.c Subject: Re: typedefing arrays Keywords: kludge hack bogus Message-ID: Date: 5 Jun 89 21:50:32 GMT References: <4636@alvin.mcnc.org> Organization: Rutgers Univ., New Brunswick, N.J. Lines: 67 Cc: bumby In article <4636@alvin.mcnc.org> spl@mcnc.org (Steve Lamont) writes: > Gentlefolk: > > . . . . . . > > Now to the nub of my question: > > Is it possible to do something like > > typedef int vertex[3]; > > vertex *v; > > v = ( vertex *) malloc( sizeof( vertex ) * some_number ); > > . . . . . . > > So, to the question before the house. Is this a sensible thing to do? > Is it even valid C (as I say, I can get both Microsoft 5.1 and BSD 4.3 C > compilers to swollow it)? How do I reference individual elements > (v[0], v[1], v[2]) as I am able to in the first instance (v->x, v->y, > v->z)? Do I have to resort to klugey constructs to use this construction > profitably? Or should I just forget the whole thing? You are really just setting up v as an array, as the following program illustrates. #include #define N 5 void *malloc( int ); typedef int vertex[3]; main() { vertex *v; int i,j; v = ( vertex *) malloc( sizeof( vertex ) * N ); for ( i = 0 ; i < N ; ++i ) for( j = 0 ; j < 3 ; ++j ) v[i][j] = i*i + j; for ( i = 0 ; i < N ; ++i ) printf( "row %3d: %8d %8d %8d\n" , i , v[i][0] , v[i][1] , v[i][2] ); } /* output: row 0: 0 1 2 row 1: 1 2 3 row 2: 4 5 6 row 3: 9 10 11 row 4: 16 17 18 */ It seems like good C to me. -- --R. T. Bumby ** Math ** Rutgers ** New Brunswick ** (in one form or another for all kinds of mail) [bumby@math.rutgers.edu]