自己记录下的一些心得,以便自己以后能够回顾。
定义两个自己的链表节点,stIn和stOut。 list_head即为Linux中List的使用。
链表stIn保存了1-16个节点(不包括头),其中a和b的值依次为1到16。
遍历链表stIn的list_head,即可得到每个节点的a和b的值。
out_head = (struct stOut*)(&in_head);
此句非常重要!将in_head地址指向的内存框成struct stOut的类型,out_head中存的地址也是&in_head,不过访问该内存时,看成是struct stOut类型。
可以遍历out_head的list_head,可以得到每个节点的a的值,而对于out_head节点来说,b是透明的,尽管它每个节点存的地址和in_head的节点地址相同,
但是它不能够获取b的值,这样便限制了对b值的访问。
其实从根本来说,内存中每个节点的a和b仅存了一次,只是stIn和stOut的类型链表以不同方式访问罢了。
struct stIn
{
u8 a;
struct list_head h;
u8 b;
};
struct stOut
{
u8 a;
struct list_head h;
};
struct stIn in_head;
struct stIn *ptr_in;
struct list_head *pos;
struct stOut *ptr_out;
struct stOut *out_head;
u8 i = 0;
INIT_LIST_HEAD(&in_head.h);
for (i = 1; i <= 16; i++) /*往链表中添加自己的节点*/
{
ptr_in = (struct stIn *) malloc(sizeof(struct stIn));
ptr_in->a = i;
ptr_in->b = i;
printf("%d ", ptr_in->a);
INIT_LIST_HEAD(&ptr_in->h);
list_add_tail(&ptr_in->h, &in_head.h);
}
printf("\n");
out_head = (struct stOut*)(&in_head);
list_for_each(pos, &in_head.h)
{
ptr_in = (struct stIn*)list_entry(pos, struct stIn, h);
printf("%d ", ptr_in->a);
}
list_for_each(pos, &out_head->h)
{
ptr_out = (struct stOut*)list_entry(pos, struct stOut, h);
printf("%d ", ptr_out->a);
}