提问的帖子:
#include<iostream.h>
class Base
{
public:
int x;
int y;
int h[2];
char a;
char b[3];
char c[1];
};
void main()
{
Base dd;
cout << sizeof(dd) << endl;
}
为什么结果输出为24?
帖子地址:http://community.csdn.net/Expert/topic/5478/5478106.xml?temp=.6268732
//----------------------------------------------------------
1) struct MyStruct
{
int dda;
int dda1;
double type ;
short duan ;
int xx;
int ss;
int kk;
};//输出
s 0x0012FF60
&s.dda 0x0012FF60
&s.dda1 0x0012FF64
&s.type 0x0012FF68
&s.duan 0x0012FF70
&s.xx 0x0012FF74
----------------------------------
32
32
0
4
8
16
20
24
28
Press any key to continue
2) struct MyStruct
{
int dda;
double dda1;
int type ;
short duan ;
int xx;
int ss;
int kk;
};
输出:
s 0x0012FF58
&s.dda 0x0012FF58
&s.dda1 0x0012FF60
&s.type 0x0012FF68
&s.duan 0x0012FF6C
&s.xx 0x0012FF70
----------------------------------------
40
40
0
8
16
20
24
28
32
Press any key to continue
s 0x0012FF60
&s.dda 0x0012FF60
&s.dda1 0x0012FF68
&s.type 0x0012FF6C
&s.duan 0x0012FF70
&s.xx 0x0012FF74
----------------------------------------
32
32
0
8
12
16
20
24
28
Press any key to continue
void main()
{
MyStruct s;
cout << "s " << &s << endl;
cout << "&s.dda " << &s.dda << endl;
cout << "&s.dda1 " << &s.dda1 << endl;
cout << "&s.type " << &s.type << endl;
cout << "&s.duan " << &s.duan << endl;
cout << "&s.xx " << &s.xx << endl;
cout<< "----------------------------------------" << endl;
cout<<sizeof(MyStruct)<<endl ;
cout<<sizeof(s)<<endl ;
cout<<offsetof(MyStruct,dda)<<endl ;
cout<<offsetof(MyStruct,dda1)<<endl ;
cout<<offsetof(MyStruct,type)<<endl ;
cout<<offsetof(MyStruct,duan)<<endl ;
cout<<offsetof(MyStruct,xx)<<endl ;
cout<<offsetof(MyStruct,ss)<<endl ;
cout<<offsetof(MyStruct,kk)<<endl ;
}
{
double dda;
int dda1;
int type ;
short duan ;
int xx;
int ss;
int kk;
};
输出:
//----------------------------------------------------------
C++中的结构体与sizeof
Type
|
Alignment
|
char
|
在字节边界上对齐
|
short (16-bit)
|
在双字节边界上对齐
|
int and long (32-bit)
|
在4字节边界上对齐
|
float
|
在4字节边界上对齐
|
double
|
在8字节边界上对齐
|
structures
|
单独考虑结构体的个成员,它们在不同的字节边界上对齐。
其中最大的字节边界数就是
该结构
的字节边界数。
|
|
MSDN原话:Largest alignment requirement of any member
|
可学习参考得其他关于对齐的帖子:
http://www.cppblog.com/cc/archive/2006/08/01/10765.html
http://blog.csdn.net/wqf363/archive/2006/11/26/1415628.aspx
http://blog.csdn.net/yanjun_1982/archive/2005/10/17/507871.aspx
http://dev.csdn.net/article/56/56202.shtm
http://dev.csdn.net/article/48/48195.shtm
----------------------------------
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>