如何确定域在结构中的字节偏移量,怎样用结构成员名访问对应成员?
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
结束!
#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
结束!
相关文章推荐
- error MSB6006: “LC.exe”已退出
- iOS 蓝牙编程
- 前端<a>标签打开新的选项卡
- 验证码的读秒数-js
- 用系统地图实现定位
- 关于C++的网站
- DirectShow 使用时个人整理的一些常见问题和解决方案
- [CareerCup] 11.8 The Rank of Number 数的排行
- Exception in thread HouseKeeper 解决办法
- 1030 Got error -1 from storage engine
- Redis的复制流程
- Xocde7 里面Xib的使用
- 详解十个网页设计技巧
- C++中使用函数返回引用的作用
- LOAD,GET;FIND,ITERATOR;MERGE,SAVEORUPDATE,LOCK的区别
- Android——继承SimpleAdapter重写自己的getView
- ABAP 总结(部分)
- Android——继承SimpleAdapter重写自己的getView
- 防止字典参数缺少发生意外崩溃的解决方法
- 《活动》游戏功能制作总结