微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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=%ld\n",(long) offsetof(struct s,i),c),d),a));
       printf("sizeof(struct s)=%ld\n",(long) sizeof(struct s));

       exit(EXIT_SUCCESS);
   }

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐