另类的结构体赋值语法

再看linux kernel代码的时候发现的东东

 

static struct inet_protocol tcp_protocol = {
    handler:    tcp_v4_rcv,
    err_handler:    tcp_v4_err,
    next:       IPPROTO_PREVIOUS,
    protocol:   IPPROTO_TCP,
    name:       "TCP"
};

 

开始不晓得啥意思,原来是这样的。

 

struct inet_protocol
{
    int         (*handler)(struct sk_buff *skb);
    void            (*err_handler)(struct sk_buff *skb, u32 info);
    struct inet_protocol    *next;
    unsigned char       protocol;
    unsigned char       copy:1;
    void            *data;
    const char      *name;
};

 

原来意思是将handler赋值成tcp_v4_rcv, err_hander赋值成tcp_v4_err, 以此类推。

 

今天又发现一种赋值的形式:

 

static struct inet_protocol tcp_protocol = {
    .handler=    tcp_v4_rcv,
    .err_handler=    tcp_v4_err,
    .next=       IPPROTO_PREVIOUS,
    .protocol=   IPPROTO_TCP,
    .name=       "TCP"
};

 

前面加个点,后面加个等号,这样都可以。

 


下面是一个获得结构体偏移的方法。


#include <stdio.h>

struct AA
{
        int a;
        char b;
}B,C;

int main()
{
        B.a = 4;
        B.b = 'a';
        printf("%p/n", &B); 
        int pB = (int)&B;    //这时 pB是B结构体的地址
        printf("%x/n", pB);

 

        // 这样是获得B结构体中的内容
        printf("B.a is %d, B.b is %c/n", ((struct AA*)(pB))->a, ((struct AA*)(pB))->b );

 

         // 用一个特殊的0作为 结构AA的基地址, 此时在取某个成员的地址,可以得到这个成员在结构中

         // 的偏移
         printf("offset of a is %d/n", &(((struct AA*)(0))->b)  );

        return 0;
}

 

 

输出内容:

 

hman@linux-plog:~> ./a.out
0x804a01c
804a01c
B.a is 4, B.b is a
offset of a is 4


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值