您的位置:首页 > 其它

如何确定域在结构中的字节偏移量,怎样用结构成员名访问对应成员?

2015-10-22 11:01 267 查看
ANSI C在<stddef.h>中定义了offsetof()宏,用offsetof(struct_type,name)可以计算出成员name在结构struct type中的偏移量,如果处于某种原因,需要自己实现这个功能,可以使用下面这样的代码:
#define offsetof(type, name) (size_t) ((char*)&((type *)0)->name-(char *)((type *)0))
解释:类型转换后的空指针的减法是为了能正确计算出偏移,强制转换成char *指针可以确保计算出的偏移是字节偏移
那如何根据结构成员名来引用结构中的这个成员呢?
struct struct_np {…; int name; …};
int offset = offsetof(struct struct_np,name);
struct struct_np test;
*(int *)((char *)&test+offset)=100;

这样既可将100赋值给机构中的name成员。

验证代码:
1 #include <stdio.h>
2
3 #define offsetn(type,n) ((size_t) ((char *)&((type*)0)->n-(char *)((type *)0)))
4
5 struct test_offset{
6 char a;
7 short b;
8 int c;
9 long d;
10 double e;
11 long long f;
12 };
13
14 int main(int argc, char **argv){
15 struct test_offset tot;
16 size_t offset = offsetn(structtest_offset, d);
17 printf("offset of d = %d\n", (int)offset);
18 long *ld =(long *)((char *)&tot+offset);
19 *ld = 100;
20 printf("the value of long d =%ld\n", tot.d);
21 return 0;
22

运行结果:
offset of d = 8
the value of long d =100

结束!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: