【问题标题】:Why does this structure has the size of 100 bytes?为什么这个结构的大小是 100 字节?
【发布时间】:2021-05-19 15:30:14
【问题描述】:

我试图了解在以下示例中如何分配填充字节(在 C 编程语言中),但我无法理解。 “STUDENT”结构的大小为 100 字节。在尝试添加额外字节时,我未能达到 100,最接近的是 104 和 88。我按照我对分配方法的考虑方式分别放入圆括号(104)和方括号(88)。如果有人能在下面的示例中解释填充字节是如何分配的,我将不胜感激。

我有一个基于 x64 的处理器,我使用 Visual Studio Code 进行编译。

#include <stdio.h>

void main()
{
    typedef struct
    {
        int day, month, year;
    } DATE;

    typedef struct
    {
        char name[40];          // 40 bytes  
        DATE registration_date; // 12 bytes (+4 padding bytes) 
        int study_year;         // 4 bytes (+12 padding bytes) [+8 padding bytes]
        int group;              // 4 bytes (+12 padding bytes) [+8 padding bytes]
        int grades[10];         // 10 bytes (+6 padding bytes) [+2 padding bytes]

    } STUDENT;

    STUDENT student;
    printf("Bytes: %d\n", sizeof(student)); // 100
    printf("The adress of name: %d\n", &student.name[40]); // 6422244
    printf("The adress of registration_date: %d\n", &student.registration_date); // 6422244
    printf("The adress of study_year: %d\n", &student.study_year); // 6422256
    printf("The adress of group: %d\n", &student.group); // 6422260
    printf("The adress of grades: %d\n", &student.grades[10]); // 6422304
} 

【问题讨论】:

  • int Grades[10] 是 40 个字节,它是一个包含 10 个元素的 int 数组。
  • 这个结构中没有填充。
  • 您可以使用offsetof检查布局。

标签: c struct padding sizeof


【解决方案1】:

我有 100 个字节。您在 grades 中计算了每个 int 1 个字节。没有填充该结构,因为没有任何东西要求比 4 字节更高的对齐方式。

【讨论】:

    【解决方案2】:
        typedef struct
        {
            char name[40];          // 40 bytes  
            DATE registration_date; // 12 bytes (no padding) 
            int study_year;         // 4 bytes (no padding)
            int group;              // 4 bytes (no padding)
            int grades[10];         // 40 bytes (no padding)
                            // TOTAL : 100 bytes
    

    【讨论】:

      猜你喜欢
      • 2019-02-03
      • 2015-06-05
      • 2014-12-29
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 2013-11-19
      • 1970-01-01
      • 2010-11-08
      相关资源
      最近更新 更多