How many elements are in my arrays?
Karl Heuer
karl at haddock.ima.isc.com
Tue Jun 5 10:13:46 AEST 1990
In article <6644.26663D46 at puddle.fidonet.org> cspw.quagga at p0.f4.n494.z5.fidonet.org (cspw quagga) writes:
>2) I want to find out how many elements are in my initialized arrays.
> #define num_elems(array) (sizeof(array)/(&array[1]-&array[0]))
That denominator is always 1. You mean `(sizeof(array)/sizeof(array[0]))'.
> Will this work, even in the presence of pad bytes?
Yes. Arrays have no padding (though their elements might), and sizeof()
does account for any padding.
Personally, I prefer to work with
#define endof(a) (&(a)[sizeof(a)/sizeof((a)[0])])
for (p = &a[0]; p < endof(a); ++p) ...
>3) I'd like to check at that two arrays have the same number of initializers.
> #if (num_elems(a) - num_elems(s))
> cause a deliberate compilation error
> #endif
(Note: the best way to force a compilation abort is with `#error' in ANSI C,
which was designed for that purpose; it also generates a syntax error in
pre-ANSI compilers if you put a leading blank on the line (` #error') to slip
it past the pre-ANSI preprocessor.)
> But, uh-huhm, the 'sizeof' and the pointer arithmetic is not permitted
> at pre-processing time. Any way to do this nicely?
Well, you could use `1/(num_elems(a) == num_elems(s))' in a nearby expression,
but please keep my name out of the code.
Karl W. Z. Heuer (karl at ima.ima.isc.com or harvard!ima!karl), The Walking Lint
More information about the Comp.lang.c
mailing list