百度快速收录seo工具软件,深圳seo网站排名优化,教育培训学校,photoshop手机版1.介绍
#xff01;#xff01;#xff01; offsetof 是一个宏 2.使用举例 结构体章节的计算结构体占多少字节需要先掌握#xff08;本人博客结构体篇章中已经讲解过#xff09; 计算结构体中某变量相对于首地址的偏移#xff0c;并给出说明 首先#xff0c;结构体首个…1.介绍 offsetof 是一个宏 2.使用举例 结构体章节的计算结构体占多少字节需要先掌握本人博客结构体篇章中已经讲解过 计算结构体中某变量相对于首地址的偏移并给出说明 首先结构体首个变量偏移量为0假定将首元素的首地址在0处那么往后每个元素的偏移量就为每个元素的地址这样一来取地址就可获得偏移量 #includestdio.h #includestddef.h//头函数 struct stu { int a; int b; char c; double d; }; int main() { printf(%d\n, sizeof(struct stu));//计算总共占用多少字节 printf(%d\n, offsetof(struct stu,a));//计算偏移量 printf(%d\n, offsetof(struct stu, b)); printf(%d\n, offsetof(struct stu, c)); printf(%d\n, offsetof(struct stu, d)); return 0; } 运行结果 3.模拟实现 #include stddef.h //写一个宏计算结构体中某变量相对于首地址的偏移并给出说明 struct stu { int a; int b; char c; double d; }; #define OFFSETOF(struct_type, mem_name) (int)(((struct_type*)0)-mem_name) int main() { printf(%d\n, OFFSETOF(struct stu, a)); printf(%d\n, OFFSETOF(struct stu, b)); printf(%d\n, OFFSETOF(struct stu, c)); printf(%d\n, OFFSETOF(struct stu, d)); return 0; }