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

list.h中用一个结构体的的成员就能找到整个结构体,实现方式是怎样的呢?
 

#include 

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)))

 

转载于:https://my.oschina.net/u/2330617/blog/779606

你可能感兴趣的:(list.h 结构成员找到结构体)