基礎C-位域一個填充知識

看別人提問 我的回答 有問題 驗證下

 

 

#include <stdio.h>
#include <string.h>
typedef unsigned char  uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int   uint32_t;


struct pid_tag
{
unsigned int inactive:1;
//unsigned int         :1;
//unsigned int refcount:6;
unsigned int         :0;

short pid_id;
struct pid_tag *link;
};

int main()
{

	printf("%d\r\n",sizeof(struct pid_tag));

}
//此時是12 它是4+2+4 中間的short是2但是被拉長4對齊就是4-4-4
//維持源碼 如果刪除short pid_id;結果是8
//維持源碼 如果修改short pid_id;爲int 結果是12
//
////開始考慮位域 我當時說unsigned int         :0;可以不要效果一樣
///實際測試發現 維持源碼 一旦不要unsigned int         :0;的話 那麼結果是8!
///爲什麼從12-->8了?因爲前面位域正好是1+1+6是一個char 是一個字節
///那就是1-2-4這樣的結構體 變成8了!!!!此時繼續修改代碼short改爲int結果是12因爲是1-4-4嘛
/////維持源碼刪除/unsigned int         :1;結果是12 WHY?
/////其實寫成
/*
struct pid_tag
{
unsigned int inactive:1;
unsigned int         :0;

short pid_id;
struct pid_tag *link;
};
int main()
{	printf("%d\r\n",sizeof(struct pid_tag));}
*/
//結果也是12 因爲那個unsigned int         :0的功能是一個U32後面全部寫0!!!

 

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