您的位置:首页 > 其它

list.h 结构成员找到结构体

2016-11-02 00:00 155 查看
list.h中用一个结构体的的成员就能找到整个结构体,实现方式是怎样的呢?

#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.h list_entry