0

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?

Craig Estey
  • 30,627
  • 4
  • 24
  • 48
H.Jamil
  • 73
  • 8
  • 7
    Why reinvent the wheel? The macro you're trying implement is already part of the C89/C99 standard. It's `offsetof(type, member)`, defined in `stddef.h`. – Marco Bonelli Feb 19 '21 at 00:21
  • 2
    It's a "trick". It's getting the _address_ of the [given] field. It's converting the _address_ value to an `unsigned int`. Because the base address of the given `struct` is `0`, the calculated/returned address is _equivalent_ to the offset of the field within the struct. – Craig Estey Feb 19 '21 at 00:27

0 Answers0