90 likes | 209 Views
情報処理演習 C2 構造体 について. 構造体とは. いくつかの変数を 、ひとまとめにしたもの。. struct RacingCar { // 車のタイプ int type; // 車の色 int color; };. // 車のタイプ int racingcar_type ; // 車の色 int racingcar_color ;. 構造体の定義. #include < stdio.h > int main() { struct RacingCar { int type; int color; };
E N D
構造体とは • いくつかの変数を、ひとまとめにしたもの。 structRacingCar { // 車のタイプ inttype; // 車の色 int color; }; // 車のタイプ intracingcar_type; // 車の色 intracingcar_color;
構造体の定義 #include <stdio.h> int main() { structRacingCar { int type; int color; }; RacingCarc1; RacingCarc2; c1.type = 10; c1.color = 2; c2.type = 20; c2.color = 5; printf("c1 type=%d, color=%d\n",c1.type,c1.color); printf("c2 type=%d, color=%d\n",c2.type,c2.color); return 0; } 構造体変数の作成 構造体変数への代入 構造体変数の使用
構造体の定義と変数 structRacingCar { int type; int color; }; RacingCar c1; RacingCar c2; type color 定義は設計図のようなもの c1 c2 実際の変数は設計図から作った車のようなもの
なぜ構造体が必要か • プログラムが大きくなると、変数がたくさんになる。 • 変数がたくさんになると、わけが分らなくなる。 • そこで、構造体で関連する変数をひとまとめにして、整理する。 int ivalue1; int ivalue2; double counter=0; intp,q,r,s; int color; int type; intneko, inu, kirin; intcgengo_ha_sukidesuka; inta,b,c; intcnt = 0; struct values { int ivalue1; int ivalue2; }; structRacingCar { double counter=0; intp,q,r,s; int color; int type; }; struct c2 { intneko, inu, kirin; intcgengo_ha_sukidesuka; inta,b,c; }; intcnt = 0;
構造体と配列 structRacingCar { int type; int color; }; RacingCar cars[3]; cars[0].type = 1; cars[1].color = 2; 構造体配列変数の作成 構造体配列変数への代入
構造体とポインタ structRacingCar { int type; int color; }; RacingCar car; RacingCar* p_car = &car; p_car->color = 1; 構造体変数の作成 構造体ポインタの作成、car変数のアドレスをセット ポインタによる変数への代入 car.color = 1;と同じ。
構造体変数の引数 structRacingCar { int type; int color; }; int function1(RacingCar c){...} int function2(RacingCar c[3]){...} int function3(RacingCar* p_c){...} int main(){...} 関数とmainの両方で構造体を使いたい場合、両方を含む位置(関数とmainの外側)で定義する。 構造体変数(コピー) 構造体配列変数(ポインタ) 構造体変数ポインタ
構造体の中に構造体 structEngine { int manufacture; int date; }; structRacingCar { Engineengine; int type; int color; } エンジンを表す構造体 レーシングカー構造体に エンジン構造体の変数を入れる