c语言限制访问链表元素的一种机制

自己记录下的一些心得,以便自己以后能够回顾。

定义两个自己的链表节点,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);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值