首页 > 解决方案 > 为什么这个结构的大小是 100 字节?

问题描述

我试图了解在以下示例中如何分配填充字节(在 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
} 

标签: cstructpaddingsizeof

解决方案


    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

推荐阅读