授業内容

Download Report

Transcript 授業内容

情報基礎演習B
後半第4回
担当 岩村
TA 谷本君
前回の復習(part 1)

ポインタの演算
 配列の添え字と同じ
double a[10], *pa;
pa=&a;
このとき、*(pa+3) と a[3]は同じものを表す
前回の復習(part 2)

メモリ(配列)の動的な確保
 必要な理由
 配列(int
data[10];のこと)では、配列の大きさ
をコンパイル前に決めなければいけない
 でも、プログラムを実行した後に配列の大きさ
を決めたい!!!
mallocを使う
前回の課題

任意の個数の数字をソートするプログラムを
作成しなさい
 要素数は最初に入力してもらう
 mallocを使う
ソートのプログラム
#include<stdio.h>
void swap(int *a, int *b) {
int tmp;
tmp =*a;
*a = *b;
*b = tmp;
}
for(i = 0; i < 9; i++){
for(j = i+1; j < 10; j++){
if(data[i] > data[j]){
swap(&data[i],&data[j]);
}
}
}
for(i = 0; i < 10; i++)
printf("%d ", data[i]);
printf("\n");
int main (void){
int data[10], i, j;
for(i = 0; i < 10; i++){
printf("Input: ");
scanf("%d", &data[i]);
}
return(1);
}
ソートのプログラム(課題の解答)
n
for(i = 0; i < 10; i++){
#include<stdio.h>
printf("Input: ");
#include <stdlib.h> malloc, free, exitのため
scanf("%d", &data[i]);
void swap(int *a, int *b) {
}
int tmp;
n-1
配列の大きさの入力
tmp =*a;
n
for(i = 0; i < 9; i++){
*a = *b;
for(j = i+1; j < 10; j++){
*b = tmp;
if(data[i] > data[j]){
}
swap(&data[i],&data[j]);
}
int main (void){
}
int data[10], i, j;
ポインタの宣言
}
int *data, n;
n
printf("n:"); scanf("%d", &n);
data=(int *)malloc(sizeof(int)*n);
if (data==NULL) {
printf("Cannot allocate memory.\n");
exit(1);
メモリ(配列)の確保
}
for(i = 0; i < 10; i++)
printf("%d ", data[i]);
printf("\n");
free(data); メモリの解放
return(1);
}
後半の予定
関数
2. ポインタ(前半)
3. ポインタ(後半) & メモリの動的確保
4. 構造体 & ファイルの入出力
5. 文字列処理 & コマンドライン引数の処理
(または、ポインタのポインタ & 2次元のメモリの
動的確保)
1.
構造体

関連のある変数をまとめて扱う方法
 人(プログラマー)にとって考えやすい
 一般に、行う処理は同じ
例)5人分の身長と体重を扱うとき
例)5人分の身長と体重を扱うとき

構造体を使わない場合

構造体を使う場合
 メンバの参照
 メンバを参照するときは
“.”(ドット)をつける
struct hitoという新しい変数
の型を定義
変数名.メンバ
サンプルプログラム1(構造体)
構造体の定義
メンバの参照
struct data型の配列hitoを宣言
サンプルプログラム1と同等のプログラム
(構造体を使わない)
typedef演算子

新しいデータ型を定義する
typedef 既存のデータ型 新しいデータ型
 例1
typedef int seisuu;
seisuu a;
int a;と同じ
 例2
typedef struct hito ningen;
ningen a;
struct hito a;と同じ
ファイルの入出力
データの読み込み
 データの書き込み


C言語では、ファイルポインタを介してファイ
ルを扱う
書式
ファイルポインタの宣言
FILE *fp;
 ファイルのオープン
fp=fopen(“ファイル名”, “モード”);

 モード
r: 読み込み(ファイルがなければエラー)
 w: 書き込み(既にファイルがあれば破棄して上書き)
 a: 追加(ファイルがあれば。なければwと同じ)


ファイルのクローズ
fclose(fp);
入出力関数

書式付きファイル入出力
 fprintf(fp,”文字列等のフォーマット”,

変数…)
printfとの違いはファイルポインタを指定すること
 fscanf(fp,”フォーマット”,
&変数…)
scanfとの違いはファイルポインタを指定すること
 ファイル中のデータは空白やタブ、改行で区切られる


他に、1文字単位や1行単位の入出力関数な
どがある
サンプルプログラム2(ファイルへの出力)
#include<stdio.h>
#include<stdlib.h>
int main(void) {
FILE *fp;
fp=fopen("test.txt","w");
if (fp==NULL) {
printf("Cannot open file.\n");
exit(1);
}
fprintf(fp,"hello!!\n");
fclose(fp);
return(0);
}
ファイルポインタの宣言
ファイルのオープン
ファイルのオープンを確認
(オープンに失敗した場合
は終了)
データの書き出し
ファイルのクローズ
ファイルをオープンした後は
ファイルポインタを使う
サンプルプログラム3
(ファイルからの入力)
書き込みの場合との相違点
#include<stdio.h>
#include<stdlib.h>
int main(void){
int data, i, n;
FILE *fp;
fp=fopen("readtest.txt","r");
if (fp==NULL) {
printf("Cannot open file.\n");
exit(1);
}
fscanf(fp,"%d", &n);
for (i=0; i<n; i++) {
fscanf(fp,"%d", &data);
printf("%d\n",data);
}
fclose(fp);
return(0);
}