结构中不同成员的存储形式并不是像想像中那样,一个接着一个的分配内存空间。如某些机器的整型变量的长度是4个字节,同时它需要起始存储位置能够被4整除。

如下代码:

 

#include<stdio.h>
#include<stddef.h>
struct D
{
    char a;
    int b;
    char c;
    float d;
    char e;
    double f;
    char g;
    int h[20];
}data1;
struct F
{
    double f;
    float d;
    int b;
    int h[20];
    char a;
    char c;
    char e;
    char g;
}data2;
struct E
{
    int a;
    char b;
    char c;
};
int main()
{
    printf("size of struct D:%d\n",sizeof(struct D));
    printf("size of struct F:%d\n",sizeof(struct F));
    printf("size of struct F:%d\n",sizeof(struct E));
    printf("\nstruct D:\n");
    printf("   char a: %d\n",offsetof(struct D,a));
    printf("    int b: %d\n",offsetof(struct D,b));
    printf("   char c: %d\n",offsetof(struct D,c));
    printf("  float d: %d\n",offsetof(struct D,d));
    printf("   char e: %d\n",offsetof(struct D,e));
    printf(" double f: %d\n",offsetof(struct D,f));
    printf("   char g: %d\n",offsetof(struct D,g));
    printf("int h[20]: %d\n",offsetof(struct D,h));
    printf("     h[0]: %d\n",offsetof(struct D,h[0]));
    printf("     h[1]: %d\n",offsetof(struct D,h[1]));
    printf("    h[19]: %d\n",offsetof(struct D,h[19]));
    printf("%\nstruct F:\n");
    printf(" double f: %d\n",offsetof(struct F,f));
    printf("  float d: %d\n",offsetof(struct F,d));
    printf("    int b: %d\n",offsetof(struct F,b));
    printf("int h[20]: %d\n",offsetof(struct F,h));
    printf("     h[0]: %d\n",offsetof(struct F,h[0]));
    printf("     h[1]: %d\n",offsetof(struct F,h[1]));
    printf("    h[19]: %d\n",offsetof(struct F,h[19]));
    printf("   char a: %d\n",offsetof(struct F,a));
    printf("   char c: %d\n",offsetof(struct F,c));
    printf("   char e: %d\n",offsetof(struct F,e));
    printf("   char g: %d\n",offsetof(struct F,g));
}
View Code

相关文章:

  • 2022-12-23
  • 2021-09-11
  • 2021-08-25
  • 2022-12-23
  • 2021-11-13
  • 2022-12-23
  • 2021-10-21
  • 2021-10-31
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-10
  • 2022-12-23
  • 2021-04-24
  • 2021-09-12
相关资源
相似解决方案