了解C++结构大小

kio*_*o89 7 c++ struct sizeof

请考虑以下代码:

struct CExample  {
    int a; 
}            

int main(int argc, char* argv[]) {  

    CExample ce1;  
    CExample ce2;  

    cout << "Size:" << sizeof(ce1) << " Address: " << &ce1 << endl;   
    cout << "Size:" << sizeof(ce2) << " Address: " << &ce2 << endl;   

    CExample ceArr[2];
    cout << "Size:" << sizeof(ceArr[0])<< " Address: "<< &ceArr[0] <<endl;
    cout << "Size:" << sizeof(ceArr[1])<< " Address: "<< &ceArr[1] <<endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出示例:
ce1:Size = 4,地址:0039FAA0
ce2:Size = 4,地址:0039FA94
ceArr [0]:Size = 4,Address:0039FA84
ceArr [1]:Size = 4,Address:0039FA88

使用代码,前两个对象(ce1和ce2)的地址之间有一个12字节,但是数组中的对象之间只有4个字节的差异.

我认为数据对齐会与问题有关,但我仍然难过.知道这里到底发生了什么吗?

Ben*_*ley 15

因为数组中的对象必须是连续的.在堆栈上连续声明的对象(在源代码中,而不是机器中)不是[必须是连续的],尽管它们可以是.


Bil*_*eal 6

标准对此没有任何说明.编译器可以自由地在项目之间插入它想要的任何填充.

(如果我不得不猜测,我猜你的编译器在调试模式下实现某种形式的堆栈保护/ canary(并且你在调试模式下编译))