【C语言】内存对齐实验

环境

x86_64 GNU/Linux

缺省

C++:

//test.cpp
 #include <iostream>

 using namespace std;

 struct st1
 {
     char a ;
     int  b ;
     short c ;
 };

 struct st2
 {
     short c ;
     char  a ;
     int   b ;
 };

 int main()
 {
     cout<<"sizeof(st1) is "<<sizeof(st1)<<endl;
     cout<<"sizeof(st2) is "<<sizeof(st2)<<endl;
     return 0 ;
 }

编译运行:

root@debian:~/test# g++ test.cpp -o testcpp
root@debian:~/test# ./testcpp
sizeof(st1) is 12
sizeof(st2) is 8

C:

#include <stdio.h>

 struct st1
 {
     char a ;
     int  b ;
     short c ;
 };

 struct st2
 {
     short c ;
     char  a ;
     int   b ;
 };

 int main()
 {
     printf("sizeof(st1) is %d
",sizeof(struct st1));
     printf("sizeof(st2) is %d
",sizeof(struct st2));
     return 0 ;
 }

编译运行:

root@debian:~/test# gcc test.c -o testc
root@debian:~/test# ./testc
sizeof(st1) is 12
sizeof(st2) is 8

C++与C运行结果一样:成员相同的结构体,sizeof大小不同。

指定1字节对齐

#include <stdio.h>

#pragma pack(1)

 struct st1
 {
     char a ;
     int  b ;
     short c ;
 };

 struct st2
 {
     short c ;
     char  a ;
     int   b ;
 };

 int main()
 {
     printf("sizeof(st1) is %d
",sizeof(struct st1));
     printf("sizeof(st2) is %d
",sizeof(struct st2));
     return 0 ;
 }

运行结果:

root@debian:~/test# gcc test.c -o testc
root@debian:~/test# ./testc
sizeof(st1) is 7
sizeof(st2) is 7

指定2字节对齐

root@debian:~/test# gcc test.c -o testc
root@debian:~/test# ./testc
sizeof(st1) is 8
sizeof(st2) is 8

参考:

经验分享 程序员 微信小程序 职场和发展