1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

構造体のサンプル

Posted at

構造体: 複数の異なる型をまとめる方法

以下、生徒のデータを構造体で管理するサンプル

# include <stdio.h>
# include <string.h>

// 構造体タグ(省略可)を元に新しい型をつくる方法
typedef struct {
    // 項目 = メンバ
    char name[64]; // 名前
    int year;      // 学年
    int clas;      // クラス
} student;

void input_student(student *data); // student型のポインタ変数の宣言
void show_student(student data);

int main(void){
    const int SIZE = 3;
    // 初期化
    student data[SIZE]; // 構造体名 実体名;

    for(int i = 0; i < SIZE; i++){
        input_student(&data[i]);
    }
    printf("==============\n");
    for(int i = 0; i < SIZE; i++){
        show_student(data[i]);
    }

    return 0;
}

void input_student(student *data){
    // ポインタとアロー演算子によるアクセス
    // 構造体の実態のポインタ変数名->メンバ名
    printf("名前は?\n-> ");
    scanf("%s", data->name);
    printf("学年は?\n-> ");
    scanf("%d", &data->year);
    printf("クラスは?\n-> ");
    scanf("%d", &data->clas);
    printf("---\n");
}

void show_student(student data) {
    printf("入力された名前: %s\n", data.name);
    printf("入力された学年: %d\n", data.year);
    printf("入力されたクラス: %d\n", data.clas);
    printf("---\n");
}
入出力
名前は?
-> 佐藤
学年は?
-> 3
クラスは?
-> 1
---
名前は?
-> 鈴木
学年は?
-> 2
クラスは?
-> 2
---
名前は?
-> 木村
学年は?
-> 1
クラスは?
-> 3
---
==============
入力された名前: 佐藤
入力された学年: 3
入力されたクラス: 1
---
入力された名前: 鈴木
入力された学年: 2
入力されたクラス: 2
---
入力された名前: 木村
入力された学年: 1
入力されたクラス: 3
---

参考
苦しんで覚えるC言語 複数の型をまとめる
【C言語入門】構造体の使い方(struct、ポインタ、アロー演算子)

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?