零指针和结构体偏移量

零指针和结构体偏移量

转自:http://hi.baidu.com/debugtime/item/42ce11ca5d063d24ef4665c6


定义一个结构体

struct A
{
...

int a;
char b;
short c;

...

}

其中已知int a=100;

取得a的地址 int* address=&a

把0强制转换为A类型的指针(A*)0,则得到一个理论上的以基址0开始的A结构体,

则可以通过&((A*)0->a)的到这个假想结构体的a的地址,由于基址为0,也就是

得到了a元素在结构体中的偏移量,结合之前取得的a的地址int* address;

address-&((A*)0->a),即得到该结构体的基址。强制转换为A类型即可,如下:

(A*)(address-&((A*)0->a)),

----------------------------------------------------------------------------------------------------

DDK中有这样一个宏:

#define CONTAINING_RECORD(address,type,field) ((type*)((PCHAR)(address)-(ULONG_PTR)(&((type*)0)->field)))

就是根据这个原理来获取结构实例基地址的。

CONTAINING_RECORD 宏返回一个结构实例的基地址,该结构的类型和结构所包含的一个域(成员)地址已知。

PCHAR CONTAINING_RECORD(
IN PCHAR Address,
IN TYPE Type,
IN PCHAR Field
);
Parameters

参数
Address
Pointer to a field in an instance of a structure of type Type.
指向Type类型结构实例中某域(成员)的指针。
Type
The name of the type of the structure whose base address is to be returned. For example, type IRP.
需要得到基地址的结构实例的结构类型名。
Field
The name of the field pointed to by Address and which is contained in a structure of type Type.
Type类型结构包含的域(成员)的名称。


Return Value

返回值

Returns the address of the base of the structure containing Field.

返回包含Field域(成员)的结构体的基地址
### C/C++ 结构体成员偏移量计算 在C/C++编程语言中,结构体成员的偏移量是指某个成员相对于结构体起始地址的距离。这个距离可以通过`offsetof`宏来获取。 #### 使用 `offsetof` 宏计算偏移量 宏`offsetof`用于计算指定类型的结构体成员相对于结构体起始位置的偏移量。其定义如下: ```c #define offsetof(type, member) ((size_t)&(((type*)0)->member)) ``` 此宏接受两个参数:一个是结构体类型`type`;另一个是结构体内的成员名`member`。通过将强制转换为目标结构体指针并访问目标成员,再取该成员的地址,最终减去结构体基址(即0),得到的就是成员相对于结构体开头的位置偏移值[^1]。 下面是一个具体的例子展示如何使用`offsetof`宏以及对比`sizeof`操作符的结果: ```c #include <stdio.h> #include <stddef.h> /* For offsetof */ #include <string.h> typedef struct { char ch; short sh; int i; } MyStruct; int main() { printf("Offset of 'ch': %zu\n", offsetof(MyStruct, ch)); printf("Offset of 'sh': %zu\n", offsetof(MyStruct, sh)); printf("Offset of 'i' : %zu\n", offsetof(MyStruct, i)); // Print size of the structure and its members. printf("\nSizeof MyStruct: %zu bytes.\n", sizeof(MyStruct)); printf("Sizeof char : %zu byte(s).\n", sizeof(char)); printf("Sizeof short : %zu byte(s).\n", sizeof(short)); printf("Sizeof int : %zu byte(s).\n", sizeof(int)); return 0; } ``` 这段程序会打印出各个字段在其所属结构体中的实际偏移量,并显示整个结构体及其各组成部分所占用的空间大小。需要注意的是,在某些平台上由于内存对齐的原因,相邻成员之间的间隔可能不是最小化存储所需的字节数目,而是按照编译器默认设置进行了调整[^3]。 对于变长结构体而言,虽然可以直接用`sizeof`获得固定部分的整体尺寸,但对于动态增长的部分则无法直接适用。此时可以借助于`offsetof`配合其他手段间接实现对其总长度的估算[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值