一个关于sizeof()的问题

已毕业程序员 2012-08-12 11:39:48
typedef struct {int i;char c; char str[4];}S s; 为什么sizeof(s)输出为12呢?不是9吗?
...全文
144 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
RLib 2012-08-12
  • 打赏
  • 举报
回复
sizeof
qq120848369 2012-08-12
  • 打赏
  • 举报
回复
4+1+4=9,向4对齐到12
tongzhipeng5699 2012-08-12
  • 打赏
  • 举报
回复
结构体对齐问题,可以看
http://blog.csdn.net/liukun321/article/details/6974282
希望对你有帮助。
fzamygsd 2012-08-12
  • 打赏
  • 举报
回复
搜 内存对齐
氰客 2012-08-12
  • 打赏
  • 举报
回复
建议楼主了解一下字节对齐,目测楼主的环境是 4字节对齐 第二个 char 类型会因为字节对齐而占4个字节,所以是 12!
IVERS0N 2012-08-12
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 的回复:]

4+1+4=9,向4对齐到12
[/Quote]

UP
中才德创 2012-08-12
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
建议楼主了解一下字节对齐,目测楼主的环境是 4字节对齐 第二个 char 类型会因为字节对齐而占4个字节,所以是 12!
[/Quote]呵呵!你已经告诉楼主了。
sublimepan 2012-08-12
  • 打赏
  • 举报
回复
内存对齐原则,即:
为了加快计算机的取数速度,编译器默认对内存进行字节对齐。对结构体(包括类)进行字节对齐,原则是:
1)结构体变量的首地址能够被其最宽基本类型成员的大小所整除;
2)结构体每个成员相对于结构体首地址的偏移量都是成员大小的整数倍,如有需要编译器会在成员之间加上填充字节);
3)结构体的总大小为结构体最宽基本类型成员大小的整数倍,如有需要编译器会在最末一个成员之后加上填充字节。
Gloveing 2012-08-12
  • 打赏
  • 举报
回复
#include <iostream> 
using namespace std;

#pragma pack(1)

typedef struct
{
int i;char c; char str[4];
}S;

void main()
{
S s;
cout<<sizeof(s)<<endl; //输出9

}

#pragma pack(1)//这句关键
#pragma pack( [ n] )

Specifies packing alignment for structure and union members. Whereas the packing alignment of structures and unions is set for an entire translation unit by the /Zp option, the packing alignment is set at the data-declaration level by the pack pragma. The pragma takes effect at the first structure or union declaration after the pragma is seen; the pragma has no effect on definitions.

Gloveing 2012-08-12
  • 打赏
  • 举报
回复
#include <iostream> 
using namespace std;

#pragma pack(1)

typedef struct
{
int i;char c; char str[4];
}S;

void main()
{
S s;
cout<<sizeof(s)<<endl; //输出9

}

#pragma pack(1)//这句关键
#pragma pack( [ n] )

Specifies packing alignment for structure and union members. Whereas the packing alignment of structures and unions is set for an entire translation unit by the /Zp option, the packing alignment is set at the data-declaration level by the pack pragma. The pragma takes effect at the first structure or union declaration after the pragma is seen; the pragma has no effect on definitions.

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧