C++ 中关于长度、偏移量和填充的问题

问题描述 投票:0回答:1

我是一个刚刚开始学习C++的初学者。在学习数据结构的时候,有一个关于sizeof的问题,想请教一下。

#include <iostream>
using namespace std;

typedef char String[9];

// Definition of Student Record
struct StudentRecord
{
    String firstName;
    String lastName;
    int id;
    float gpa;
    int currentHours;
    int totalHours;
};

int main(int argc, const char * argv[]) {
    StudentRecord student;
    StudentRecord students[100];

    // Size of memory allocation for student
    cout << "sizeof(student): " << sizeof(student) << endl;
    // Size of memory allocation for students
    cout << "sizeof(students): " << sizeof(students) << endl;
    
    return 0;
}

在以下代码中:

cout << "sizeof(student): " << sizeof(student) << endl; 

当我打印sizeof(student)时,它返回36。但是,student的成员变量的大小明确定义为从firstName到末尾的9,9,4,4,4,4。将它们加起来,得到 34。但是作为 StudentRecord 实例的 Student 实例的大小是 36。

我很好奇这个 2 字节的差异是如何发生的。我从谷歌搜索中发现它与填充有关。因此,我知道firstName和lastName的大小均为9,id和gpa的大小均为4,加起来为8,这就是为什么添加额外的填充大小1以匹配firstName和lastName的9大小。同样,currentHours 和totalHours 也有额外的填充大小1,导致总大小为36。

我的理解正确吗?谢谢!

我想了解实际计算机上发生的填充过程。

c++ padding sizeof
1个回答
1
投票

你必须满足所有基本类型的填充要求,指针或 double 或 long 应对齐到 8 个字节,int/float 应对齐到 4 个字节,char 应对齐到 1 个字节。

struct StudentRecord
{
    char names[18];
    // char padding[2]; // done by compiler.
    int id;
    float gpa;
    int currentHours;
    int totalHours;
};

在你的对象中,你的2个字符串的总长度为9 + 9 = 18,后面跟着一个

int
,这个
int
必须对齐到4个字节,因此编译器在18之后插入2个字节的填充字符,因此 18 + 2 = 20,并且 20 % 4 = 0,现在
id
已正确对齐到 4 个字节。

© www.soinside.com 2019 - 2024. All rights reserved.