我试图理解填充字节是如何分配的(在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: %dn", sizeof(student)); // 100
printf("The adress of name: %dn", &student.name[40]); // 6422244
printf("The adress of registration_date: %dn", &student.registration_date); // 6422244
printf("The adress of study_year: %dn", &student.study_year); // 6422256
printf("The adress of group: %dn", &student.group); // 6422260
printf("The adress of grades: %dn", &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字节更高的对齐。