[C Language] Library macro offsetof

1. Introduction to offsetof

Therefore, the function of macro offsetof is:

When you pass in the type of a structure and its members , it returns the offset of that member in the structure .


 2. Use of offsetof

As follows, we use offsetof to print the offsets of member a, member b and member c relative to the first address in structure foo:

#include <stdio.h>     
#include <stddef.h>   //使用offsetof需要包含的头文件

struct stu {
  char ch;
  int sz;
  short age;
};

int main ()
{
  printf ("offsetof(struct stu,ch) is %d\n",(int)offsetof(struct stu,ch));
  printf ("offsetof(struct stu,sz) is %d\n",(int)offsetof(struct stu,sz));
  printf ("offsetof(struct stu,age) is %d\n",(int)offsetof(struct stu,age));
  
  return 0;
}

The running results are as follows:

offsetof(struct stu,ch) is 0
offsetof(struct stu,sz) is 4
offsetof(struct stu,age) is 8

 Let’s draw a picture to verify:


 3. Implementation of offsetof

The implementation of offsetof in the library function is as follows:

#define OFFSET(type,member) (size_t)&((type*)0)->member)

Let’s draw a picture to analyze the principle:

 After understanding the principle, we will also be inspired when writing our own macros. Of course, we can also use the form of member address minus the first address. Interested friends can try to write it themselves.

Guess you like

Origin blog.csdn.net/weixin_72357342/article/details/132843514