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;
}
If I compile and run the code the offset for field "salary" is 20 and it should be 20.
But if I change structure field char name[20];
to char name[30];
the offset for "salary" changes to 32 but it should be 30. if I further change structure field to char name[1];
the offset for "salary" changes to 4 but it should be 1. Why these offset value discrepancies are happening?
The second part of the question is 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?