计算一个结构体内成员地址的偏移量的两种方法

一、有时候需要需要看一下一个结构体内成员地址的偏移量,下面介绍两种实现方法。

二、实现方法。

1、方法一,包含头文件#include <stddef.h>,调用函数offsetof(struct s, i)来实现。

2、方法二,使用&(((s1*)0)->i)的形式。

三、实例测试。

1、c代码

       #include <stddef.h>
       #include <stdio.h>
       #include <stdlib.h>
 
       int main(void)
       {
           struct s {
               int i;
               char c;
               double d;
               char e;
               char a[];
           };
           typedef  struct  {
               int i;
               char c;
               double d;
               char e;
               char a[];
           }s1;
           //Output is compiler dependent 
           printf("\nmethod one:\n");
           printf("offsets: i=%ld; c=%ld; d=%ld e=%ld a=%ld\n",
                   (long) offsetof(struct s, i),
                   (long) offsetof(struct s, c),
                   (long) offsetof(struct s, d),
                   (long) offsetof(struct s, e),
                   (long) offsetof(struct s, a));
           printf("sizeof(struct s)=%ld\n", (long) sizeof(struct s));
 
           
           printf("\nmethod two:\n");
           
           printf("offsets: i=%ld; c=%ld; d=%ld e=%ld a=%ld\n",
                   (long) &(((s1*)0)->i),
                   (long) &(((s1*)0)->c),
                   (long) &(((s1*)0)->d),
                   (long) &(((s1*)0)->e),
                   (long) &(((s1*)0)->a));
           
           
             printf("sizeof(struct s1)=%ld\n", (long) sizeof(s1));
           
           exit(EXIT_SUCCESS);
       }
2、编译&执行。

3、结果显示,两种方法都可以正确的计算结构体的偏移量

猜你喜欢

转载自blog.csdn.net/asdfsadfasdfsa/article/details/87897224