Powered by SmartDoc

22 10章;構造体

22.1 残りの予定

11/26;構造体

12/ 3;休講

12/10;ポインタ

12/17;数値計算と誤差,並び替えのアルゴリズムの比較

1/ 7;復習(課題)

1/??;期末試験(筆記試験)

22.2 構造体の例

構造体は,とても便利なデータ構造.

struct [構造体タグ]宣言のリスト[変数]

宣言,定義,代入,参照.

リスト 22.2.1 構造体の例(list10-1.c)
#include <stdio.h>
#include <string.h>

/* global変数 */
/* 構造体の宣言;学生一人一人が持つべき性質を示した設計図 */
struct student {
  int id;        /* 出席番号 */
  char name[20]; /* 氏名 */
  int kokugo;    /* 国語の点 */
  int suugaku;   /* 数学の点 */
  int eigo;      /* 英語の点 */
};

int main(void);
void print_student(struct student s);

int main(void) 
{
  struct student taro; /* 学生の実体「太郎」を定義(生成) */
  struct student jiro; /* 学生の別の実体「次郎」を定義(生成) */

  /* 「太郎」のデータを代入 */
  taro.id = 10;         /* 構造体の名前.メンバ名 */
  strcpy(&taro.name[0], "Yamada"); /* Cは文字列の扱いがややこしい */
  taro.kokugo = 100;
  taro.suugaku = 85;
  taro.eigo = 60;

  /* 「次郎」のデータを代入 */
  jiro = taro; 
  jiro.id = 11;
  strcpy(&jiro.name[0], "次郎"); /* Cは文字列の扱いがややこしい */
  jiro.kokugo = 99;

  print_student(taro);
  print_student(jiro);

  return 0;
}

void print_student(struct student s)
{
  printf("出席番号:%d\n", s.id);
  printf("氏名:%s\n", &s.name[0]);
  printf("国語:%d\n", s.kokugo);
  printf("数学:%d\n", s.suugaku);
  printf("英語:%d\n", s.eigo);
  printf("合計:%d\n", s.kokugo+s.suugaku+s.eigo);
  printf("\n");

  return;
}

22.3 補足

list10-4.c

list10-5.c

構造体の変数名を宣言する別の方法 (list10-1a.c)

Rensyuu10-1.c

Rensyuu10-2.c