50分请高手解答:字节对齐的介绍

Tycool 2004-09-01 02:08:04
比如编译器的字节对齐选项介绍,
不对齐造成的问题等等
比如:
#define u8 unsigned char
#define u16 unsigned short

u8 u8One;
u16 u16Two;
struct mystruct
{
u8 m_u8AttribA;
u8 m_u8AttribB;
u8 m_u8AttribC;
u16 m_u8AttriA;
u8 m_u8AttribD;
}aStruct;
u8 u8Three;

请问这个结构的首地址变量与前后变量有否关系,会否由于编译器对齐参数而奇偶不同?
该结构改成如下的好处是否在用u8或u16指针访问时有影响?直接用成员名访问是否没影响?
struct mystruct
{
u8 m_u8AttribA;
u8 m_u8AttribB;
u8 m_u8AttribC;
u8 m_u8AttribD;//Move from behind u16
u16 m_u8AttriA;
}aStruct;
...全文
188 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
Tycool 2004-09-02
  • 打赏
  • 举报
回复
我自己找了一下,这篇不错,谢谢大家
sizeof,终极无惑
http://blog.csdn.net/freefalcon/archive/2004/07/28/54839.aspx
hcj2002 2004-09-01
  • 打赏
  • 举报
回复
http://blog.csdn.net/hcj2002/archive/2004/08/22/81638.aspx
积木 2004-09-01
  • 打赏
  • 举报
回复
is me ?
lgdpeter8 2004-09-01
  • 打赏
  • 举报
回复
what are you talking about?
积木 2004-09-01
  • 打赏
  • 举报
回复
不知道你对内存的寻址方式有多少的了解,看点代码
#include<iostream>
using namespace std;
struct S
{
int i;
char c;
};
int main()
{
S s;
s.i=1;
s.c='c';
}
mov dword ptr [ebp-8],1
;
; s.c='c';
;
mov byte ptr [ebp-4],99
xor eax,eax

计算机中有一种寻址方式,叫做直接变址寻址,如果算上字节对齐,那么变址的时候就可以以一个单位乘以倍数的方式进行简单的变换,而不用每次都计算寻址的空间,使得操作效率得到提高,如上面的汇编码,dword ptr [ebp-8],1 然后跳过4个byte,变成了byte ptr [ebp-4],99 中间就省掉了计算byte大小的语句。

看看汇编这些东西就变得很自然了。
jjyyis 2004-09-01
  • 打赏
  • 举报
回复
禁止内存对齐
#pragma pcak(push,1)

u8 u8One;
u16 u16Two;
struct mystruct
{
u8 m_u8AttribA;
u8 m_u8AttribB;
u8 m_u8AttribC;
u16 m_u8AttriA;
u8 m_u8AttribD;
}aStruct;
u8 u8Three;

#pragma pack(pop)
短歌如风 2004-09-01
  • 打赏
  • 举报
回复
楼主的两种写法在对齐时长度相同,在16位对齐时后一种更好,比较紧凑。
oo 2004-09-01
  • 打赏
  • 举报
回复
缺省情况下:
让n个字节长的成员(基本类型)以n的倍数地址开始,
比如int 4字节长,要从4的倍数地址开始,等等,
为了定义一个结构数组时,成员也满足上面的条件,
如果struct的总大小不是 max(n)的倍数,也要补成max(n)倍数。
ftkghost 2004-09-01
  • 打赏
  • 举报
回复
请问一下字节对齐是什么含意阿?
还有,他有什么具体应用?
xjp6688 2004-09-01
  • 打赏
  • 举报
回复
关注
blh 2004-09-01
  • 打赏
  • 举报
回复
for example:
aStruct as;
the address of as is 0x10000
first case:
m_u8AttribA: 0x10000
m_u8AttribB: 0x10001
m_u8AttribC: 0x10002
m_u8AttriA: 0x10004
m_u8AttribD; 0x10006


second case
m_u8AttribA: 0x10000
m_u8AttribB: 0x10001
m_u8AttribC: 0x10002
m_u8AttribD; 0x10003
m_u8AttriA: 0x10004

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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