环境
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\n",sizeof(struct st1));
printf("sizeof(st2) is %d\n",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\n",sizeof(struct st1));
printf("sizeof(st2) is %d\n",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
取消字节对齐 __attribute__ ((packed))
#include <stdio.h>
struct st1
{
char a ;
int b ;
short c ;
}__attribute__ ((packed));
struct st2
{
short c ;
char a ;
int b ;
};
int main()
{
printf("sizeof(st1) is %d\n",sizeof(struct st1));
printf("sizeof(st2) is %d\n",sizeof(struct st2));
return 0 ;
}
参考:
Linux内核:内存管理——内存对齐原则 - 知乎 (zhihu.com)
内存对齐原则 - 杜东洲 - 博客园 (cnblogs.com)文章来源:https://www.toymoban.com/news/detail-594195.html
__attribute__((packed))详解_yihui8的博客-CSDN博客文章来源地址https://www.toymoban.com/news/detail-594195.html
到了这里,关于【C语言】内存对齐实验的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!