问题描述
我试图了解以下示例中的填充字节是如何分配的(在 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
}
解决方法
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
,
我得到了 100 个字节。您在 grades
中为每个 int 计算了 1 个字节。结构没有被填充,因为没有什么要求比 4 个字节更高的对齐。