加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在c中查找结构元素的偏移量

发布时间:2020-12-16 05:50:43 所属栏目:百科 来源:网络整理
导读:struct a{ struct b { int i; float j; }x; struct c { int k; float l; }y;}z; 任何人都可以解释我如何找到int的偏移量,我们可以找到int i ????的地址 解决方法 使用offsetof()从z开始或从x的开始找到偏移量. offsetof() – 结构成员的偏移量 概要 #include
struct a
{
        struct b
        {
                int i;
                float j;
        }x;
        struct c
        {
                int k;  
                float l;
        }y;
}z;

任何人都可以解释我如何找到int的偏移量,我们可以找到int i ????的地址

解决方法

使用offsetof()从z开始或从x的开始找到偏移量.

offsetof() – 结构成员的偏移量

概要

#include <stddef.h>

   size_t offsetof(type,member);

offsetof()返回字段成员的偏移量
开始结构类型.

#include <stddef.h>
   #include <stdio.h>
   #include <stdlib.h>

   int
   main(void)
   {
       struct s {
           int i;
           char c;
           double d;
           char a[];
       };

       /* Output is compiler dependent */

       printf("offsets: i=%ld; c=%ld; d=%ld a=%ldn",(long) offsetof(struct s,i),c),d),a));
       printf("sizeof(struct s)=%ldn",(long) sizeof(struct s));

       exit(EXIT_SUCCESS);
   }

您将获得以下OUTPUT在Linux上,如果您使用GCC编译.

offsets: i=0; c=4; d=8 a=16
       sizeof(struct s)=16

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读