No. of elements in initialized array
VLD/VMB
gwyn at BRL.ARPA
Mon Mar 3 16:30:54 AEST 1986
> ... 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)?
The padding is part of the "sizeof" the structure.
#define number_of_elements(array) (sizeof(array)/sizeof(array)[0])
This works unless your C compiler is badly broken. (That CAN happen;
not very long ago I had to use one that insisted that sizeof a string
literal was equal to sizeof(char*).)
More information about the Comp.lang.c
mailing list