No. of elements in initialized array

Colin Kelley colin at vu-vlsi.UUCP
Thu Feb 27 04:17:02 AEST 1986


We've got some code that looks like: (somewhat simplified here)

struct termentry {
        char name[MAX_ID_LEN];          /* name of graphics driver */
        unsigned int xmax,ymax;         /* screen dimensions */

} term_tbl[] = {
        {"hp",    HP_XMAX,    HP_YMAX},
        {"regis", REGIS_XMAX, REGIS_YMAX},
        {"tek",   TEK_XMAX,   TEK_YMAX}
};

This code takes advantage of the C compiler's ability to count the number of
initializers for term_tbl[], and automatically dimension term_tbl[] to that
size.  However, code that must look at term_tbl[] needs to know how many
elements it has.  The solution we're using now is:

#define TERMCOUNT (sizeof(term_tbl)/sizeof(struct termentry))

This works fine on both our Pyramid and our Vaxen.  BUT...is this the preferred
technique?  Isn't it possible on some machines that the structs may have to
be padded out to some arbitrary word boundary or something in order to fit
efficiently into the array (and thus sizeof(term_tbl) may not be an integer
multiple of sizeof(struct termentry))?  Or will C compilers guarantee that that
any necessary padding will be included in sizeof(struct)?

I assume this must be a pretty common problem.  I hope someone out there
can tell me whether our code is ok as is, or if I've overlooked some obvious
solution...Thanks!

                        -Colin Kelley  ..!{psuvax1,pyrnj}!vu-vlsi!colin



More information about the Comp.lang.c mailing list