構造体 と リスト構造

Download Report

Transcript 構造体 と リスト構造

第4回ネットワークプ
ログラミング
中村 修
今日のお題

構造体とは?
 練習問題1:構造体の練習

リスト構造
 練習問題2:一方向リスト構造を作ってみる
--------(休憩)----------------
実習
 成績順に並べてみよう
 (バブルソートの練習)
構造体(structure)

構造体を用いると、複数のデータを1つのまとま
りとして取り扱うことができる
 Ex:
1人の学生に対して学籍番号と成績
struct student{
int id;
int score;
};
 異なる型も混在できる
struct student2{
char name[32];
int score;
};
構造体の定義

定義の方法
struct 構造体名{
型 メンバ名1;
型 メンバ名2;
:
:
};

使用例
struct student{
int id;
int score;
};
構造体を用いた変数

定義した構造体を用いて変数はプリミティブ
な型と同じ方法で宣言できる
 型名の変わりにstruct
int a;
sturct student b;
構造体名を用いる
構造体メンバへのアクセス(1)

構造体メンバへのアクセスは.(ドット)演算子
を用いる
 Ex:
struct studentの変数bの点数(メンバ
名:score)を表示する
struct student b = {70000000,70};
printf(“bの点数は%dです\n”, b.score);
構造体メンバへのアクセス(2)

構造体へのポインタの変数のメンバへのアクセスは
->演算子を用いる
 Ex:
struct studentの変数bの点数(メンバ名:score)を表
示する
struct student b = {70000000,70};
struct student *c = &b;
printf(“bの点数は%dです\n”, c->score);

構造体へのポインタ変数->メンバ名 は
(*構造体へのポインタ変数).メンバ名 と同意
構造体(structure)(使用例1)
Int
 構造体の定義、
main()
構造体変数の宣言
{
int i;
構造体変数の初期化
struct student{
を同時に行う場合
int id;
int score;
} students[5] = { {70001234,80},
{70204578,70},
{70157384,60},
{70355678,75},
{70207658,49} };
for(i=0;i<5;i++){
printf("student id:%d, score:%d\n",
students[i].id,
students[i].score);
}
}
構造体(structure)(使用例2)
struct student{
int id;
int score;
};
構造体の定義を分
けた場合
 変数の宣言、初期
化は同時に行って
いる

Int
main()
{
int i;
struct students[5] = { {70001234,80},
{70204578,70},
{70157384,60},
{70355678,75},
{70207658,49} };
for(i=0;i<5;i++){
printf("student id:%d, score:%d\n",
students[i].id,
students[i].score);
}
構造体(structure)(使用例3)
struct student{
int id;
int score;
};
構造体の定義を分
けた場合
 初期化は行わずに
代入を行っている。

Int
main()
{
int i;
struct students[5];
for(i=0; i<5; i++){
students[i].id = i;
students[i].score = i;
}
for(i=0;i<5;i++){
printf("student id:%d, score:%d\n",
students[i].id,
students[i].score);
}
typedefを用いる
typedef struct student{
int id;
int score;
} STUDENT;
STUDENT students[5];
練習1:構造体の練習

以下の情報をキーボードから入力し、後でま
とめて出力する。
 学籍番号
 ログイン名
 名前
リスト構造ってなぁに?
次の領域を保持することで、記憶領域を連結
する構造。
 こんなとき便利

 並びかえ
 stack
& pop
連結リスト(linked list):宣言
構造体の中に次の構造体へのポインタを格
納
struct student{
int id;
int score;
struct student *next;
}

連結リスト:メモリの確保
何人のリストが事前にわからないので、いくつ宣言
すればいいかわからない。
→ 最初のノードだけ宣言して、あとはそのつど領域を
確保する。

struct student *first;
struct student *current, *prev;
prev = NULL;
current =
(struct student *)malloc(sizeof(sturct student));
連結リスト:メンバーの情報を格納
mallocで領域を確保した後は、メンバをつい
かする。
current->id = atoi(buf_id);
current->score = atoi(buf_score);
current->next = NULL;
prev->next = current;

練習問題2:リスト構造を使おう



score.txtの中身はSFCのマークシートの出力とおな
じです。
このファイルを構造体に格納して、出力しよう。
最初の8文字が学籍番号、次の文字が点数
 strncpyをつかって、分離
 atoiを使って
文字→数値 変換
/home/kaizaki/osamuNP/4/score.txt
実習

score.txt を点数順に並べ替えて、出力する。
 出力フォーマット
id: 学籍番号, score: 点数
:
:
: