[C language advanced] implementation of offsetof macro

content

Introduction to Macros

Code 


 

offsetof is a macro, not a function!!!

Introduction to Macros

 Parameters: the first is the structure type name, the second is the structure member name

Return type: size_t unsigned integer

Referenced header file : <stddef.h>

#include <stddef.h>
struct Stu
{
	int a;//0~3
	char c;//4
	double d;//8~15
};
int main()
{
	printf("%u\n", sizeof(struct Stu));
	printf("%u\n", offsetof(struct Stu, a));
	printf("%u\n", offsetof(struct Stu, c));
	printf("%u\n", offsetof(struct Stu, d));
	return 0;
}

 

Code 

struct Stu
{
	int a;
	char c;
	double d;
};

#define OFFSETOF(struct_name, mem_name)    (int) & (((struct_name*)0) -> mem_name)


int main()
{
	printf("%d\n", OFFSETOF(struct Stu, a));
	printf("%d\n", OFFSETOF(struct Stu, c));
	printf("%d\n", OFFSETOF(struct Stu, d));
	return 0;
}

It is to specify the structure pointer as 0, and then set the address of other members - the first address , which is the last offset

Guess you like

Origin blog.csdn.net/qq_54880517/article/details/124284985