I have defined a macro that calculates the offset of a structure to any of the structure field. The Code is as follow:
#define offset(struct_name, fld_name) \
(unsigned int)&(((struct_name *)0)->fld_name)
typedef struct emp_{
char name[20];
unsigned int salary;
char designation[30];
unsigned int emp_id;
} emp_t;
int main(int argc, char **argv){
unsigned int offsetValue;
offsetValue=offset(emp_t,salary);
printf("field = %s\n","salary");
printf("offset = %d\n", offsetValue);
return 0;
}
how exactly the #define offset
macro is calculating the offset? What is &(((struct_name *)0)->fld_name)
actually doing? The outer &
denote the address but what exactly remaining (((struct_name *)0)->fld_name)
means?