C/C++語言裡面的空間節省

來源:互聯網
上載者:User

我們知道在一個結構體當中,往往為了節省記憶體空間,會花點心思進行位元組對齊。

typedef struct __aligning
{
      unsigned short n;
      unsigned int m;
      unsigned short x;
} aligning1;

針對上面的struct:aligning1,我們使用sizeof計算會得到12個位元組,顯然沒有符合4位元組對齊的方式,以下寫法更為科學:

typedef struct __aligning
{
      unsigned short n;
      unsigned short x;
      unsigned int m;
} aligning2;

此時struct會佔用8個位元組。

然而往往為了更細化,可使用bool(c++)或者enum獲得更小的容器來節省空間的,但是1個位元組已經成為下限,如果有8個成員變數,取值範圍是1和0的話,也需要8個位元組,如果節省更多的空間呢?
C經典文法類型,表示bit方式可以如下:

typedef struct __aligning
{
      unsigned n:1;
      unsigned m:1;
      ...
      unsigned t:1;
} aligning3;

這樣最多也就4個位元組,其實4個位元組可以最多表示32個成員變數,每個變數1bit;

再結合實際情況,用實際的最大值,結合位元組對齊,就可以節省更多的記憶體空間,大家在工程中不妨試試喲!



原文地址:http://my.huhoo.net/archives/2009/07/cc.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.