Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!tut.cis.ohio-state.edu!snorkelwacker!spdcc!ima!haddock!karl From: karl@haddock.ima.isc.com (Karl Heuer) Newsgroups: comp.lang.c Subject: Re: How many elements are in my arrays? Message-ID: <16789@haddock.ima.isc.com> Date: 5 Jun 90 00:13:46 GMT References: <6644.26663D46@puddle.fidonet.org> Reply-To: karl@haddock.ima.isc.com (Karl Heuer) Organization: Interactive Systems, Cambridge, MA 02138-5302 Lines: 32 In article <6644.26663D46@puddle.fidonet.org> cspw.quagga@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@ima.ima.isc.com or harvard!ima!karl), The Walking Lint