offsetof() macro

offsetof() macro

        In structure, the elements are stores in a sequential order of  their declaration. To access the displacement of an element in a structure we can use offsetof() macro in C.

       structures and union are considered as plain old data types,  which are used to bundle other datatypes. offsetof() macro can be used to get the displacement of an element in bytes from base address of the variable of a structure.This macro is written by Peter D Hipson in 1992. It is available in stddef.h header file.

#define OFFSETOF(DATATYPE, 

ELEMENT_OF_STRUCTURE) ((size_t)&(((DATATYPE *)0)-

>ELEMENT_OF_ELEMENT))

In the above syntax zero is casted to type of structure and required element's address is obtained, which is inturn casted to size_t.size_t is of type unsigned int as per standard. The final result will be the number of bytes after which the ELEMENT_OF_STRUCTURE is being placed in the structure.

#include
#include

typedef struct Test
{
   int     x;
   double  y;
   char    z;
} testtype;

main()
{
   printf("%d", offsetof(testtype, z) );
    
}

Comments