typedefing arrays

Chris Torek chris at mimsy.UUCP
Tue Jun 6 09:56:47 AEST 1989


In article <4636 at alvin.mcnc.org> spl at mcnc.org (Steve Lamont) writes:
>  Is it possible to do something like
>
>	typedef int	vertex[3];

This creates a type alias called `vertex' which means `array 3 of int'.

>	vertex	*v;

Thus, this declares v as `pointer to array 3 of int', and

>	v = (vertex *) malloc( sizeof( vertex ) * some_number );

this calls malloc with an argument of `sizeof(int [3])*n' and casts
the result to `pointer to array 3 of int'.

>My compiler will swallow it, and, if I play all sorts of funny games
>with pointer dereferencing, I can even put numbers into the array v and
>pull them out again in some semblance of correct order.  However, all of
>the solutions I come up with are inelegant, at best. 

The return from malloc, as cast and stored in v (if not nil), is suitable
for use as an `array n of array 3 of int' (I am using `n' where you have
`some_number').  To talk about the third `vertex', write

	v[2]

(the first vertex is v[0], not v[1]).  This is an object of type
`array 3 of int'; in most contexts, it is transformed into one of type
`pointer to int', which then points to the first of the three `int's.

>Is this a sensible thing to do?

Yes.

>... 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)?

v[0][0] is the first int in the first array of 3 ints; v[0][1] is the
second int in the first array of 3 ints; v[0][2] is the third int in
the first array of 3 ints.  All three exist if v != NULL and if n was
at least 1.  These can also be written as (*v)[0], (*v)[1], and (*v)[2]
respectively, and the first has yet another form, **v.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list