数据(内存)对齐

要点

  • 对齐参数一般是数据类型的大小,也可以通过编译指令指定。
  • 数据按照其类型的对齐参数在内存地址中对齐。
  • struct中的成员数据对齐之后,这个struct的sizeof()结果会变大。
  • struct本身的对齐参数等于其成员中对齐参数最大的一个。
  • struct的大小(sizeof)是其对齐参数的整数倍。
  • 32位系统中,指针类型的大小是4Bytes的,数组是成员的大小与成员的个数相乘。

实验

代码

#include “stdio.h”

// case1. memory alignment
typedef struct S00{
char A;
char a;
char b;
};

typedef struct S11{
unsigned A;
char a;
char b;
};

typedef struct S12{
char a;
int A;
char b;
};
// case2. pointer vs. array
typedef struct S21{
short* a;
};
typedef struct S22{
short a[7];
};
// case3. align as max size of member
// case3. struct as member
typedef struct S31{
S00 s[5];
};
typedef struct S32{
S12 s[5];
};

int main(int argc, char* argv[])
{
printf(”-:-. -:-. -:-. -:-. -:-. -:-. -:-. -:-. \n”);
printf(”sizeof(unsigned):\t%d\n”, sizeof(unsigned));
printf(”sizeof(int):\t%d\n”, sizeof(int));
printf(”sizeof(char):\t%d\n”, sizeof(char));
printf(”sizeof(short):\t%d\n”, sizeof(short));
printf(”sizeof(long):\t%d\n”, sizeof(long));
printf(”-:-. -:-. -:-. -:-. -:-. -:-. -:-. -:-. \n”);
printf(”sizeof(S00):\t%d\n”, sizeof(S00));
printf(”sizeof(S11):\t%d\n”, sizeof(S11));
printf(”sizeof(S12):\t%d\n”, sizeof(S12));
printf(”-:-. -:-. -:-. -:-. -:-. -:-. -:-. -:-. \n”);
printf(”sizeof(S21):\t%d\n”, sizeof(S21));
printf(”sizeof(S22):\t%d\n”, sizeof(S22));
printf(”-:-. -:-. -:-. -:-. -:-. -:-. -:-. -:-. \n”);
printf(”sizeof(S31):\t%d\n”, sizeof(S31));
printf(”sizeof(S32):\t%d\n”, sizeof(S32));
printf(”-:-. -:-. -:-. -:-. -:-. -:-. -:-. -:-. \n”);
return 0;
}

结果

-:-. -:-. -:-. -:-. -:-. -:-. -:-. -:-.
sizeof(unsigned): 4
sizeof(int): 4
sizeof(char): 1
sizeof(short): 2
sizeof(long): 4
-:-. -:-. -:-. -:-. -:-. -:-. -:-. -:-.
sizeof(S00): 3
sizeof(S11): 8
sizeof(S12): 12
-:-. -:-. -:-. -:-. -:-. -:-. -:-. -:-.
sizeof(S21): 4
sizeof(S22): 14
-:-. -:-. -:-. -:-. -:-. -:-. -:-. -:-.
sizeof(S31): 15
sizeof(S32): 60
-:-. -:-. -:-. -:-. -:-. -:-. -:-. -:-.
Press any key to continue

参考

1. 内存对齐 作者 Fang
2. 补课补课,关于C语言中的结构体对齐问题

No comments yet. Be the first.

Leave a reply

Random posts

  • 观山寨手机有感
  • 广受好评的鸟巢照
  • 中奖了,PS2
  • Solution for Matlab 7.0 R14 on XP Pro Start up Corruption
  • Re: 大家都说说自己遇到的最恐怖的老师吧