typedefing arrays

Tom Karzes karzes at mfci.UUCP
Tue Jun 6 15:03:24 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];
>
>	vertex	*v;
>
>	v = ( vertex *) malloc( sizeof( vertex ) * some_number );

Yes, you can do this.  In this case v has type "int (*)[3]", i.e., a
pointer to an array of 3 ints (or a pointer into an array of arrays
of 3 ints).  Your call to malloc should allocate "some_number" objects
of the size of vertex, which is the size of three ints (so the total
size is 3 * "some_number" ints).

To access the 2nd element (index 1) of the 21st vertex (index 20) in v,
you could write v[20][1].  Here, v[20] gets you the 21st vertex, and
v[20][1] gets you the 2nd element of that vertex.  With the structure
version you showed in your original message, if the second element of
a vertex corresponds to y, you would have written v[20].y instead.

If you add or subtract integers to or from v, it will skip past whole
instances of vertex.  I.e., (*(v + 5))[i] is the same as v[5][i].
However, beware of precedence.  The following are all equivalent:

    v[i][j]
    (*(v + i))[j]
    *(v[i] + j)
    *(*(v + i) + j)

But *(v + i)[j] is equivalent to *((v + i)[j]) which is equivalent to
*(*((v + i) + j)) or **((v + i) + j) or **(v + (i + j)) or *v[i + j]
or v[i + j][0].

If you get confused, it may help to think of how the case where vertex
is wrapped in a struct works.  I.e.,

    typedef struct {
        int     p[3];
    } vertex;

    vertex *v;

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

Then v[20][1] in the previous example becomes v[20].p[1] in this example,
and the following are all equivalent:

    v[i].p[j]
    (*(v + i)).p[j]
    (v + i)->p[j]
    *(v[i].p + j)
    *((*(v + i)).p + j)
    *((v + i)->p + j)

Note that in the second and fifth cases above your compiler would give
you a syntax error if you left off the parentheses around (*(v + i)).



More information about the Comp.lang.c mailing list