Sizeof structure members

throopw at dg_rtp.UUCP throopw at dg_rtp.UUCP
Thu Jul 17 03:35:52 AEST 1986


> lvc at danews.UUCP (Larry Cipriani)

> [How does one take sizeof a struct member without an instance of it?]
> I didn't want to define a global variable of type 'struct utmp *',
> because I didn't need it, and lint would complain because I didn't
> use it.  I could declare an external variable of type 'struct utmp *',
> that I'd never use, but this seems just as bad as the unused global.

This solution is fairly portable, and may even be legal:

        struct s {char a[3];};
        void main(){
            printf( "%d\n", sizeof( ((struct s *)0)->a ) );
        }

It works on a at least a couple of machines, and lint doesn't complain.
It may be argued that it is not legal, since it is dereferencing the
null pointer.  On the other hand, sizeof is guaranteed not to evaluate
the object being sizeofed, and to only calculate resulting types, not
values.  It's issues like these that give language lawyers headaches,
right?

--
A program without a loop and a structured variable isn't worth writing.
                                --- Alan J. Perlis
-- 
Wayne Throop      <the-known-world>!mcnc!rti-sel!dg_rtp!throopw



More information about the Comp.lang.c mailing list