Monday, November 15, 2010

Figure out size of int without using sizeof() in C

a trick using pointer arithmetic.

(int)((int*)0+1)

First, advance the pointer at address 0 by one. How many it advances depend
on the size of the pointer type.

this solution is provided by one person in MITBBS.com. Thanks.

There are at least two other ways:
1)
int a[2];

   unsigned addr0=&a[0];
   unsigned addr1=&a[1];

   size_t sizeofint=addr1-addr0;

2)
typedef struct ab {
     int a;
     int b;
   } AB;

   sizeofint=offset(b in AB)
            =(unsigned)(&((AB*)0->b))

No comments:

Post a Comment