sizeof a struct element

Fred Wright fw at fwright.net
Thu Sep 12 02:31:40 UTC 2024


On Wed, 11 Sep 2024, Hal Murray via devel wrote:

> I'm trying to cleanup the tangle in ntp_control.c that generates warnings.
> They may be actual bugs.  The problem is that the man page says long while
> the actual size may be 32 or 64 on 32 bit Linux systems.
>
> If I knew the size, the fix would be simple.  wscript has code to get the
> size of a type but I don't know the type.

Resorting to configure tests just to get type sizes is in general a bad 
idea, for aforementioned reasons.

> Can anybody write the waf code for me that will give me the size of
> ntx.errcnt if ntx is a struct timex?

You can just use sizeof().  The only caveat is that there's no way (AFAIK) 
to apply it to an element of an abstract type, so you need a concrete 
instance to apply it to.  But the concrete instance can even be just a 
pointer, as long as it's a pointer to a complete struct type.

Here's an example with a less OS-dependent struct:
---------------------------------------------------------------------------
/* Test of sizeof for a struct element. */

#include <stdio.h>
#include <sys/time.h>

int
main(int argc, const char *argv[])
{
   struct timeval *tvp;

   (void) argc; (void) argv;

   printf("Size of struct timeval's tv_sec = %d bytes\n",
          (int) sizeof(tvp->tv_sec));
   return 0;
}
---------------------------------------------------------------------------

You can similarly determine the type of a struct element with typeof(), 
though that can get a bit tricky depending on compiler version and 
pedantry level.

Fred Wright


More information about the devel mailing list