list.h 结构成员找到结构体
2016-11-02 00:00
155 查看
list.h中用一个结构体的的成员就能找到整个结构体,实现方式是怎样的呢?
上段代码中 offset 为struct node 中成员 d 的偏移地址长度,具体意思是吧0地址强制转化为
一个 (Node*)指针然后取出成员 d 的地址, 就相当于 (&(node.d) - 0)即为 d 的偏移量。
(如果没有&地址符这就是一个非法访问了)然后再用 成员 d 的实际地址减去偏移量就为整个机构体的地址,再强制转化为结构体就行了,
如下:
list.h中的list_entry(ptr, type, member) 就是如此
#include <stdio.h> struct node { int a; int b; double c; char d; }; typedef struct node Node; int main() { int offset = (unsigned long)(&((Node*)0)->d); printf("the offset of d is %d\n",offset ); }
上段代码中 offset 为struct node 中成员 d 的偏移地址长度,具体意思是吧0地址强制转化为
一个 (Node*)指针然后取出成员 d 的地址, 就相当于 (&(node.d) - 0)即为 d 的偏移量。
(如果没有&地址符这就是一个非法访问了)然后再用 成员 d 的实际地址减去偏移量就为整个机构体的地址,再强制转化为结构体就行了,
如下:
struct node { int a; int b; double c; char d; }; typedef struct node Node; int main() { Node nodetmp = { 1 ,2 ,3.0 ,'a'}; char * nodetmp_p; int offset = (unsigned long)(&((Node*)0)->d); printf("the offset of d is %d\n",offset ); nodetmp_p = (&(nodetmp.d)) - offset; printf(" the a is %d \n",((Node *)nodetmp_p)->a); printf(" the a is %d \n",((Node *)nodetmp_p)->b); printf(" the a is %f \n",((Node *)nodetmp_p)->c); printf(" the a is %c \n",((Node *)nodetmp_p)->d); }
list.h中的list_entry(ptr, type, member) 就是如此
/** * list_entry - get the struct for this entry * @ptr: the &struct list_head pointer. * @type: the type of the struct this is embedded in. * @member: the name of the list_struct within the struct. */ #define list_entry(ptr, type, member) \ ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
相关文章推荐
- 怎样根据结构成员的地址找到结构体的地址(list_entry)
- 标记化结构初始化语法---结构体成员前加小数点
- [c]如何通过结构体元素找到结构体?
- 如何计算结构体大小和结构体中成员的内存偏移
- 通过结构体某个成员的地址计算结构体首地址
- c++根据结构体成员指针找到结构体指针
- 结构体中调用结构体成员到底用->还是用.
- 标记化结构初始化语法 在结构体成员前加上小数点 如 “.open .write .close ”C99编译器
- 如何通过一个结构体成员变量的地址找到该结构体的首地址
- C#传递结构体地址(或者结构体成员的地址)给C/C++ DLL
- 结构体成员地址在结构体内的偏移
- 访问结构体结构成员的示例
- 标记化结构初始化语法---结构体成员前加小数点
- 由结构体成员地址计算结构体地址——节点地址的函数list_entry()原理详解
- 由结构体成员地址计算结构体地址——list_entry()原理详解
- 如何通过一个结构体成员变量的地址找到该结构体的首地址?[备忘]
- list_entry(ptr, type, member)——知道结构体内某一成员变量地址,求结构体地址
- 标记化结构初始化语法 在结构体成员前加上小数点 如 “.open .write .close ”C99编译器
- list用remove实现对结构体成员的删除
- 如何通过结构体元素找到结构体?