2014-03-06 98 views
0

我只是试图检查内存如何分配给结构对象,它占用了更多的空间,我期望的。我使用64位Windows操作系统和Mi​​crosoft Visual Studio 2010(我认为它的32位),所以可以解释为什么它的打印52字节?为什么结构大小不正确

struct test { 
    int year;// should take 4 byte 
    string title;// how much bytes would take ? in my case taking 31 bytes ? 
    double date;//should take 8 byte 
    int month;// should take 4 byte 
    } mine; 

int main() 
{ 
cout << " size is: "<<sizeof(mine);//printing 52 ? 
cout << " size is: "<<sizeof(struct test);//printing 52 ? 
    return 0; 
} 
+4

编译器增加了对路线填充.. – Maroun

+0

那是'string' ='标准:: string'还是什么?如果它是自定义的类/结构体,则应该发布适用类的精简版本(它不需要包含比变量更多的 - 不需要任何函数)。 – Dukeling

+0

看看#pragma pack并阅读有关字节对齐。 – Totonga

回答

1

注意

sizeof(struct) >= sizeof(its members) 

由于每个成员可能以前的成员之后对齐到最低的地址,其满足

mod(address/sizeof(member)) == 0 

例如,考虑这个struct

struct s { 
    char c; 
    int i[2]; 
    double d; 
} 

内存可能看起来像:

+-------------------------------------------------+ 
| c | | | | i[0] | i[1] | | | | | .. v .. | 
+-------------------------------------------------+ 
    ^^^   ^^^^ 
+1

它是否真的必须按其大小对齐?我相信一般来说,对齐要求可能不同。 – Angew

+0

@Angew我认为你是对的..我会研究并编辑我的答案,谢谢。 – Maroun

+0

@Angew显然不是。 'struct X {char x [1000000]; }'不需要一百万(或更多)的对齐。然而,对齐不能大于尺寸。 –

相关问题