[問題] sizeof

看板C_and_CPP (C/C++)作者 (平凡)時間10年前 (2015/08/22 11:26), 10年前編輯推噓3(3012)
留言15則, 7人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 小弟實作 結構體, 並且sizeof. 想問一下, 各別size是4 1 4, 為什麼stu size是12不是9? 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) #include <stdio.h> int main(int argc, char *argv[]) { struct student{ int id; char name; long number; }; struct student stu; printf("stu size=%d\n",sizeof(stu)); printf("id size=%d\n",sizeof(stu.id)); printf("name size=%d\n",sizeof(stu.name)); printf("number size=%d\n",sizeof(stu.number)); return 0; } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.25.178.63 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1440213987.A.E34.html

08/22 11:37, , 1F
#pragma pack
08/22 11:37, 1F
回S大: 可以再說詳細點嗎?

08/22 11:48, , 2F
編譯器可以自行決定如何擺放
08/22 11:48, 2F

08/22 11:49, , 3F
struct裡的成員之間可能會留空
08/22 11:49, 3F
原來如此~~ ※ 編輯: GooLoo (114.25.178.63), 08/22/2015 11:53:33

08/22 12:23, , 4F
一般是照順序擺,可是int等比較大的資料一定要擺在
08/22 12:23, 4F

08/22 12:23, , 5F
4的倍數(一般)的位址上,所以中間留空
08/22 12:23, 5F

08/22 12:24, , 6F
可以查查alignment
08/22 12:24, 6F

08/22 16:14, , 7F
編譯器會幫你塞在固定大小的開頭...要讓他緊密相連
08/22 16:14, 7F

08/22 16:14, , 8F
可以查查一樓的關鍵字
08/22 16:14, 8F

08/22 22:45, , 9F
aligment,印象中compiler為了優化速度而會對旗最大空間
08/22 22:45, 9F

08/22 22:45, , 10F
的成員(講錯請指證)
08/22 22:45, 10F

08/22 22:55, , 11F
是對齊 4 的倍數 , 不過 compiler alignment 規則還真的.
08/22 22:55, 11F

08/22 22:55, , 12F
不好猜/觀查
08/22 22:55, 12F

08/22 22:58, , 13F
基本上操作空間太大. 也不一定是 4 的倍數
08/22 22:58, 13F

08/22 23:10, , 14F
在 C++11 後也只確定是落在 power of 2
08/22 23:10, 14F

08/22 23:50, , 15F
了解!!謝謝樓上和樓樓上指證:)
08/22 23:50, 15F
文章代碼(AID): #1Lr-lZuq (C_and_CPP)
文章代碼(AID): #1Lr-lZuq (C_and_CPP)