Declaring pointer to array of structures, within a structure

Andrew Koenig ark at alice.UucP
Wed Jun 4 00:41:38 AEST 1986


> Now this seems to work perfectly well, and lint says nary a word about
> this code except for a complaint about the possible alignment problem
> from the cast of malloc(), which I presume is normal.  But what bugs me
> is that in my typedef of bar, I don't say that member d is a pointer to
> an ARRAY of struct foo, I just say that it is a pointer to one struct foo.
> Is this kosher, or have I violated some subtle but important distinction
> between arrays and pointers to them?  Remember, I'd like to be able to
> treat member d as I would the name of any other array in referencing
> the memory it points to.

You're doing the right thing.

In C, the size of an array can only be a constant.  However,
the name of an array is almost always translated to a pointer
to its zeroth element.  Thus you can use a pointer in essentially
all contexts where you might use an array.  The only difference
I can think of is that sizeof(BAR->d) will be the size of a
pointer rather than the amount of memory you allocated.

Incidentally, you don't need to write (BAR->d)[5] because
-> binds more tightly than [] .  You can therefore write BAR->d[5] .



More information about the Comp.lang.c mailing list