疑念は探究の動機であり、探究の唯一の目的は信念の確定である。

数学・論理学・哲学・語学のことを書きたいと思います。どんなことでも何かコメントいただけるとうれしいです。特に、勉学のことで間違いなどあったらご指摘いただけると幸いです。 よろしくお願いします。くりぃむのラジオを聴くこととパワポケ2と日向坂46が人生の唯一の楽しみです。

C言語の構造体とtypedefとsizeofについて

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;はしません。理由はよくわかりませんが。



僕から以上