Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!cs.utexas.edu!uunet!mfci!karzes From: karzes@mfci.UUCP (Tom Karzes) Newsgroups: comp.lang.c Subject: Re: typedefing arrays Keywords: kludge hack bogus Message-ID: <884@m3.mfci.UUCP> Date: 6 Jun 89 05:03:24 GMT References: <4636@alvin.mcnc.org> Sender: karzes@mfci.UUCP Reply-To: karzes@mfci.UUCP (Tom Karzes) Organization: Multiflow Computer Inc., Branford Ct. 06405 Lines: 58 In article <4636@alvin.mcnc.org> spl@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)).