How many elements are in my arrays?

cspw quagga cspw.quagga at p0.f4.n494.z5.fidonet.org
Sat Jun 2 03:45:40 AEST 1990


 
Some questions about ANSI C.
 
1) Did the 'offsetof' macro make it into the finals?  I notice
   it is missing in TurboC 2.0, but present in a couple of other
   compilers that also claim ANSI compatibility.
 
2) I want to find out how many elements are in my initialized arrays.
 
   char s[][5]  = { "sun", "mon", "tues"  ... };
 
   #define num_elems(array)  (sizeof(array)/(&array[1]-&array[0]))
 
   Will this work, even in the presence of pad bytes?  (ie will the sizeof
   the total structure always be an exact multiple of the size of the
   padded individual elements, or is the compiler allowed to insert
   different padding sizes at the beginning or end?).
   Is there an easier way that works in all cases?
 
3) I'd like to check at that two arrays have the same number of initializers.
 
   int  a[]     = { 0,1,2,3,4, ...  };
   char s[][5]  = { "sun", "mon", "tues"  ... };
 
   I'd like this check at compile time, so I'd like to be able to write
 
   #if (num_elems(a) - num_elems(s))
      cause a deliberate compilation error
   #endif
 
   But, uh-huhm, the 'sizeof' and the pointer arithmetic is not permitted
   at pre-processing time.   Any way to do this nicely?
 
 
Pete

--
EP Wentworth - Dept. of Computer Science - Rhodes University - Grahamstown.
Internet: cspw.quagga at f4.n494.z5.fidonet.org
Uninet: cspw at quagga
uucp: ..uunet!m2xenix!quagga!cspw



--  
uucp: uunet!m2xenix!puddle!5!494!4.0!cspw.quagga
Internet: cspw.quagga at p0.f4.n494.z5.fidonet.org



More information about the Comp.lang.c mailing list