C言語の構造体の書き方についてまとめました。
また、構造体のサイズを取得するときのsizeofについてまとめました。
typedefをtypedefすることは基本的にないそうです。
また、構造体をsizeofをすると自動的にパディングします。余計なビットが加わります。
#include <stdio.h> // without typedef struct st_example { char char_; int int_; }; // with typedef (1) typedef struct { char char_; short short_; } st_example_typedef; //with typedef (2) typedef struct _st_example { char char_; int int_; } st_example_; // we do not define typedef struct st_example_ *example_ptr; typedef struct _st_example *example_ptr; int main(void) { // without typedef struct st_example ins; ins.char_ = 'a'; ins.int_ = 1; printf("ins.char_ = %c\n", ins.char_); printf("ins.int_ = %d\n", ins.int_); printf("sizeof(struct st_example) = %lu\n", sizeof(struct st_example)); printf("-------------------\n"); // with typedef (1) st_example_typedef ins_td; ins_td.char_ = 'b'; ins_td.short_ = 2; printf("ins_td.char_ = %c\n", ins_td.char_); printf("ins_td.short_ = %d\n", ins_td.short_); printf("sizeof(st_example_typedef) = %lu\n", sizeof(st_example_typedef));
実行結果
ins.char_ = a
ins.int_ = 1
sizeof(struct st_example) = 8
ーーーーーーーーーー
ins_td.char_ = b
ins_td.short_ = 2
sizeof(st_example_typedef) = 4
最初の構造体st_example
のサイズはint
が4バイトであるため、char
の1バイトプラス3バイト分、追加されます。したがって、sizeof(struct st_example)
は4 + 1 + 3 = 8バイトとなります。
一方で、次の構造体st_example_typedef
のサイズはshort
が2バイトですので、char
の1バイトプラス1バイト分、追加されます。したがって、sizeof(st_example_typedef)
は2 + 1 + 1 = 4バイトとなります。
また、一度typedef
したものをさらにtypedef
はしないそうです。
つまり、typedef struct _st_example *example_ptr;
はしますが、typedef st_example_ *example_ptr;
はしません。理由はよくわかりませんが。
僕から以上