3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C言語における構造体の宣言の仕方を理解しよう。

Last updated at Posted at 2020-02-27

構造体を使用するメリット

  • 文字列を含め、全要素を一括代入ができる。
  • 再帰的に使用して、リスト構造を作れる。

*リスト構造については最後の参考URLにわかりやすい解説があります。

構造体の型を宣言する

structの後に構造体名を付けて宣言

struct 構造体名{
};
  • Example
struct student {
	int year;	/* 学年 */
	int number;	/* 出席番号 */
	char name[64];	/* 名前 */
	double stature;	/* 身長 */
	double weight;	/* 体重 */
};

新しい型として構造体の型を宣言する

C言語では、新しい型を宣言するtypedef(タイプデフ)が用意されています。

typedef 新しい型の形 新しい型名
struct student_tag {
	int year; /* 学年 */
	int number; /* 出席番号 */
	char name[64]; /* 名前 */
	double stature; /* 身長 */
	double weight; /* 体重 */
};
/*
構造体student_tag型のstudent型を宣言
宣言以降、studentを型名として使用することができる。
*/
typedef struct student_tag student;

上記のtypedefを使用した宣言の省略した書き方

typedef struct student_tag {
	int year; /* 学年 */
	int number; /* 出席番号 */
	char name[64]; /* 名前 */
	double stature; /* 身長 */
	double weight; /* 体重 */
} student;

さらに省略した書き方

typedef struct {
	int year;	/* 学年 */
	int number;	/* 出席番号 */
	char name[64];	/* 名前 */
	double stature;	/* 身長 */
	double weight;	/* 体重 */
} student;

再帰的に構造体を利用する際の書き方

ポインタを使用する場合は、今まで説明した省略形が使えません。定義されていない型が、型の中に出てきてしまうため、コンパイル時にエラーが発生します。

なので、先に型を宣言する方法を使います。

typedef struct list LIST;
struct list{
  unsigned int number;
  char name[256];
  LIST *next;
} ;

もしくは見にくいかもしませんが、より再帰をイメージしやすいように書くと下記のようになります。

typedef struct List List;
struct list{
  unsigned int number;
  char name[256];
  List *next;
} ;

Listの構造体を持つList型を宣言してから、Listの構造体を宣言しています。

C言語では、型の中身である構造体が決まっていなくても、宣言できてしまうのです。

なぜかと言えば、宣言しているのは、__Listという言葉を型を示す言葉として使用しますよ!__ということであって、領域を確保しているわけではないからです。

使用する関数の中で宣言

関数の中で宣言することで使えるようになります。

typedefで型名として宣言しない場合

int main(void)
{
	struct student data;
	return 0;
}

typedefで型名として宣言する場合

int main(void)
{
	student data;
	return 0;
}
参考URL

異なる型の変数をまとめる - 苦しんで覚えるC言語
https://9cguide.appspot.com/16-01.html

リスト構造をC言語プログラムの実例を用いて解説 | だえうホームページ
https://daeudaeu.com/programming/c-language/list-structure/

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?