Monday, January 28, 2008

Find the size of a variable (type)

/* Find the size of an variable */
#define sizeof_var( var ) \\
((size_t)(&(var)+1) - (size_t)(&(var)))

/* Find the size of a data type */
#define sizeof_type( type ) \\
(size_t)((type*)1000 + 1 ) - (size_t)((type*)1000)
The above codes are from the following link

for example, if you want to find the size of an integer (sizeof(int)), you may declare an array and compare the addresses of elements.
int a[2];
int x = (int) &a[1];
int y = (int) &a[0];
printf ("%d - %d = %ld\n", &a[1], &a[0], x - y);

No comments:

Post a Comment