騰訊刷題筆記

筆記心得

騰訊刷題筆記 (sizeof問題)

  • struct的size問題
#include <iostream>
using namespace std;
struct xx{
    //long long _x1;
    int _x3;
    char _x2;
    char _x4[2];
   // static int _x5;
};
//int xx::_x5;
int main()
{
    cout<<sizeof(xx)<<endl;
    cout << "Hello world!" << endl;
    return 0;
}

參考內容內存對齊

32位操作系統

  1. sizeof問題
    • long 4位;
    • int 4位;
    • char 1位;
    • float 4位;
    • double 8位;
      在C語言中,struct 中的static屬性並不會佔用struct的存儲空間
  2. 內存對齊問題
    • 在struct中,內存對齊會使用'數據成員'中最長的那一位,進行內存對齊;
  3. 順序問題
    • 在代碼中的變量定義順序會影響sizeof的長度
    • 如上面 _x3與_x2目前的位置,得出的sizeof的長度爲按照 int 類型進行內存對齊,此時的 sizeof 的長度爲 4+1+2 -> 8;
    • 如果交換_x2與_x3的順序的話,得到的sizeof的長度爲 1(4)+4+2(4) = 12

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章