在 c 中查找结构元素的偏移量 [英] Finding offset of a structure element in c

查看:40
本文介绍了在 c 中查找结构元素的偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct a
{
    struct b
    {
        int i;
        float j;
    }x;
    struct c
    {
        int k;  
        float l;
    }y;
}z;

谁能解释一下如何找到int k的偏移量,以便我们可以找到int i的地址?

Can anybody explain me how to find the offset of int k so that we can find the address of int i?

推荐答案

使用 offsetof() 查找距 z 开头或 z 开头的偏移量代码>x.

Use offsetof() to find the offset from the start of z or from the start of x.

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

offsetof() - offset of a structure member

概要

   #include <stddef.h>

   size_t offsetof(type, member);

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

offsetof() returns the offset of the field member from the start of the structure type.

示例

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

       exit(EXIT_SUCCESS);
   }

如果您使用 GCC 编译,您将在 Linux 上获得以下输出:

You will get the following output on a Linux, if you compile with GCC:

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

这篇关于在 c 中查找结构元素的偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆