久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

C語言中結構體struct怎么對齊

164次閱讀
沒有評論

共計 1936 個字符,預計需要花費 5 分鐘才能閱讀完成。

這篇文章主要介紹“C 語言中結構體 struct 怎么對齊”,在日常操作中,相信很多人在 C 語言中結構體 struct 怎么對齊問題上存在疑惑,丸趣 TV 小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C 語言中結構體 struct 怎么對齊”的疑惑有所幫助!接下來,請跟著丸趣 TV 小編一起來學習吧!

struct,相互關聯的元素的集合,每個元素都有自己的內存空間;每個元素在內存中的存放是有先后順序的,就是定義時候的順序;一個 struct 所占的總的內存大小,并不是各個元素所占空間之和,而是存在字節對齊的問題.
struct 中的每個元素相對于結構體的首地址的偏移量能被該元素的 size 整除 (某些編譯器, 如果該元素的 size 4,則偏移量能被 4 整除即可).
測試代碼:

[xdb@localhost test]$ cat test.cpp
#include  cstdio 
#include  iostream 
using namespace std;
#define LL long long 
struct E1 {
 int a; char b; char c;
struct E2 {
 char b; int a; char c;
struct E3 {
 char a; short b; int c; LL d;
struct E4 {
 int c; LL d; char a; short b;
struct E5 {
 char a1,a2,a3,a4,a5,a6;
struct E6 {
 char a1,a2,a3;
struct E7 {
 struct E5 elem5;
 struct E6 elem6;
 LL a;
struct E8 { char a[9];
struct E9 {
 struct E8 elem8;
 LL a;
struct E10 {
 char a;
int main() {
 puts( ----  E1 
 cout   sizeof(E1)   endl;
 printf(%x %x %x %x\n ,  e1,  e1.a,  e1.b,  e1.c); 
 puts( ----  E2 
 cout   sizeof(E2)   endl;
 printf(%x %x %x %x\n ,  e2,  e2.b,  e2.a,  e2.c); 
 puts( ----  E3 
 cout   sizeof(E3)   endl;
 printf(%x %x %x %x %x\n ,  e3,  e3.a,  e3.b,  e3.c,  e3.d); 
 puts( ----  E4 
 cout   sizeof(E4)   endl;
 printf(%x %x %x %x %x\n ,  e4,  e4.c,  e4.d,  e4.a,  e4.b); 
 puts( ----  E5 
 cout   sizeof(E5)   endl;
 puts( ----  E6 
 cout   sizeof(E6)   endl;
 puts( ----  E7 
 cout   sizeof(E7)   endl;
 printf(%x %x %x %x\n ,  e7,  e7.elem5,  e7.elem6,  e7.a);
 puts( ----  E8 
 cout   sizeof(E8)   endl;
 puts( ----  E9 
 cout   sizeof(E9)   endl;
 printf(%x %x %x\n ,  e9,  e9.elem8,  e9.a);
 puts( ----  E10 
 cout   sizeof(E10)   endl;
 return 0;
[xdb@localhost test]$

編譯, 執行

[xdb@localhost test]$ g++ test.cpp -o test
[xdb@localhost test]$ ./test
----  E1
6021a0 6021a0 6021a4 6021a5
----  E2
6021a8 6021a8 6021ac 6021b0
----  E3
6021c0 6021c0 6021c2 6021c4 6021c8
----  E4
6021d0 6021d0 6021d8 6021e0 6021e2
----  E5
----  E6
----  E7
602200 602200 602206 602210
----  E8
----  E9
602230 602230 602240
----  E10
[xdb@localhost test]$

到此,關于“C 語言中結構體 struct 怎么對齊”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注丸趣 TV 網站,丸趣 TV 小編會繼續努力為大家帶來更多實用的文章!

正文完
 
丸趣
版權聲明:本站原創文章,由 丸趣 2023-08-03發表,共計1936字。
轉載說明:除特殊說明外本站除技術相關以外文章皆由網絡搜集發布,轉載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 简阳市| 阿拉善盟| 新疆| 拉萨市| 沽源县| 乳源| 桦甸市| 策勒县| 韶关市| 家居| 墨玉县| 宁晋县| 浦江县| 永善县| 贵港市| 原阳县| 武义县| 灵石县| 龙井市| 通辽市| 珠海市| 逊克县| 柳州市| 革吉县| 阳城县| 新兴县| 金平| 延吉市| 博客| 石河子市| 迭部县| 广元市| 隆德县| 新安县| 光泽县| 大冶市| 阳原县| 南陵县| 诏安县| 泰州市| 舞钢市|