linux offsetof在用户态C语言实现及示例

若需转载,请注明出处


linux系统提供的offsetof方法是得到一个结构体中的一个成员字段的此结构体中的偏移字节,现在用户态进行实现。


在用户态进行实现的例子:得到一个结构体中的子结构体中的某一个字段的值

                         假设前题:只知道大结构的类型、子结构体的名字、子结体的某一字段的名字                                  

                                思路:先得到子结体中的字段相对于大结构体的偏移量,然后再得到此字段的地址值,然后再得到此字段的类型,由此类型把得到的地址值进行强制转换后就可以得到此字段的值了,代码实现:


#include <stdio.h>

#include <stdlib.h>

//子结构体

typedef struct student{

  int age;
  int length;
  char c;
  long width;
  char mm[4];
  int nn;
}ST_STUDENT;

//大结构体

typedef struct school
{
  int schNo;
  ST_STUDENT first;
  int sumpeple;
}ST_SCHOOL;

//示例为求得子结构体中的char c的值

int main()

{
    int offset, ret, nowadd;
    char *ch = malloc(sizeof(ST_SCHOOL));
    strcpy(ch, "yygydjkthh");
    printf("ch addr is 0x%x char str is %s\n", ch, ch);
    ST_SCHOOL sccxzz;
    sccxzz.first.c = 'a';
    offset = (char *)(&(((ST_SCHOOL *)ch)->first.c)) - ch;
    nowadd = (char *)((char *)&sccxzz + offset);
    typeof(sccxzz.first.c) m = *((typeof(sccxzz.first.c) *)nowadd);
    printf("offset is %d m is %c m len is %d\n", offset, m, sizeof(m));
    printf("ch str is %s\n", ch);
    free(ch);
    exit(0);
}

其中:

//下行得到char c字段相对于大结构体的偏移量

offset = (char *)(&(((ST_SCHOOL *)ch)->first.c)) - ch;

//下行为得到char c的地址

nowadd = (char *)((char *)&sccxzz + offset);

//下行为得到求得的char c地址的值并保存到以char c字段类型声明的一个变量中

//其中typeof为得到某一变量的类型,下行也即为: char m = *((char *)nowadd);

typeof(sccxzz.first.c) m = *((typeof(sccxzz.first.c) *)nowadd);

运行结果为:

ch addr is 0x9191008 char str is yygydjkthh
first.c is a
sccxzz add is 0xbfda205c nowadd is 0xbfda2068 first.c add is 0xbfda2068
offset is 12 m is a m len is 1
ch str is yygydjkthh


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值