後期の中間試験までで、構造体について説明の予定。
構造体がなかったら
構造体がない場合、同じようなデータが複数現れると、 配列にしたりすることになるが、そのバリエーションでは、 単純に配列にするだけでは不十分となる。
#define SIZE 50 char name[ SIZE ][ 20 ] ; int math[ SIZE ] ; int sci[ SIZE ] ; int eng[ SIZE ] ; // 複数の学科 char m_name[ SIZE ][ 20 ] ; int m_math[ SIZE ] ; : int ei_name[ SIZE ][ 20 ] ; int ei_math[ SIZE ] ; :
m_name , ei_name といった名前を使い分ける必要があり、 同じような処理をまとめることが難しい。
構造体を使う
複数の異なるデータを、1つの型としてまとめるものが、 構造体。最近のオブジェクト指向では、構造体の概念を 拡張したものなので、必ず使えるようになっておく必要あり。
struct Student { char name[ 20 ] ; int math ; int sci ; int eng ; } ; struct Student saitoh ; struct Student data[ 50 ] ; saitoh.math = 80 ; strcpy( saitoh.name , "t-saitoh" ) ; strcpy( data[ 0 ].name , "aoyama" ) ; data[ 0 ].eng = 90 ;
基本は、構造体変数名.要素名 で参照すれば、普通の変数と同じ。
構造体は入れ子にすることもできる。
struct Birthday { int year ; int month ; int day ; } ; struct Person { char name[ 20 ] ; int age ; struct Birthday bday ; } ; struct Person saitoh = { "t-saitoh" , 48 , { 1965 , 2 , 7 } } ;
このように、データ構造をブロック化することを、データの構造化と呼ぶ。 同じように、if (…) { while(…) { … } } といった、ような 入れ子にすることは、手続きの構造化と呼ばれる。 この2つの構造化を合わせて、構造化プログラミングと呼ぶ。