offsetof宏的实现,计算结构体中某变量相对于首地址的偏移

用一个宏定义offsetof求一个结构体struct里某个变量相对struc的编移量
如:struct student
{
int a;
char b;
double c;
}
则:
offsetof(student,a); //等于0
offsetof(student,b);//等于4

首先,ANSI C标准允许任何值为0的常量被强制转换成任何一种类型的指针,并且转换结果是一个NULL指针,所以我们的第一步(struc*)0,就是把0转换为一个struc类型的指针。

&(((s*)0)->m)的意图并非想存取s字段内容,而仅仅是计算当结构体实例的首址为((s*)0)时m字段的地址。编译器根本就不生成访问m的代码,而仅仅是根据s的内存布局和结构体实例首址在编译期计算这个(常量)地址,这样就完全避免了通过NULL指针访问内存的问题。”

如果不加(size_t)则输出的是十六进制

代码如下:

#include<stdio.h>

#define offsetof(struc,memb) ((size_t)&(((struc*)0)->memb))

int main()
{
	typedef struct student
	{
		char name[10];//10
		int numb;//10+2+4
		long tel;//16+4
	}student;

	int offsetof_name = offsetof(student, name);
	printf("offsetof_name=%d\n", offsetof_name);

	int offsetof_numb = offsetof(student, numb);
	printf("offsetof_numb=%d\n", offsetof_numb);

	int offsetof_tel = offsetof(student, tel);
	printf("offsetof_tel=%d\n", offsetof_tel);

	printf("sizeof(student)=%d\n", sizeof(student));

	return 0;
}

结果:
offsetof宏的实现,计算结构体中某变量相对于首地址的偏移

上一篇:Intern Day83 - C# - 索引器Indexer的使用原因+作用+使用


下一篇:JS将手机号中间四位数变成 *