typedefing arrays

Richard Bumby bumby at math.rutgers.edu
Tue Jun 6 07:50:32 AEST 1989


In article <4636 at alvin.mcnc.org> spl at mcnc.org (Steve Lamont) writes:

> Gentlefolk:
> 
> 		    . . . <stuff omitted> . . .
>
>   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 );
> 
> 		  . . . <more stuff omitted> . . .
> 
>   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 <stdio.h>
#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 at math.rutgers.edu]



More information about the Comp.lang.c mailing list