LoginSignup
0
1

More than 1 year has passed since last update.

【C】初めてのC言語(10. 構造体配列)

Last updated at Posted at 2022-06-16

はじめに

学習環境

  • 今回はpaiza.ioのC言語のエディタを使いました。

やりたい事

社員番号 社員名 部署名
1 Sato Sales
2 Suzuki Development
3 Takahashi Sales

サンプルコード

  • 社員名と部署名はこのコード中では変更されないので、char* ではなく const char*としました。
    • この点については @angel_p_57 さんのコメントに基づいて修正しました。
    • 例えば「コード中で部署名が変更される可能性がある」という場合は char* になるのかもしれませんが、現時点ではよく分かりません。
main.c
#include <stdio.h>

// 構造体:社員型
typedef struct employee {
    int id;             // 社員番号
    const char* name;   // 社員名
    char* deptName;     // 部署名
} Employee;

int main(void){
    // 社員リストの作成
    Employee empList[3];

    empList[0].id = 1;
    empList[0].name = "Sato";
    empList[0].deptName = "Sales";

    empList[1].id = 2;
    empList[1].name = "Suzuki";
    empList[1].deptName = "Development";
    
    empList[2].id = 3;
    empList[2].name = "Takahashi";
    empList[2].deptName = "Sales";
    
    // 社員リストの表示
    int arySize = sizeof(empList) / sizeof(Employee);
    
    for (int i=0; i<arySize; i++) {
        printf("社員番号:%d、社員名:%s、部署名:%s\n",
            empList[i].id,
            empList[i].name,
            empList[i].deptName);
    }
    return 0;
}
実行結果
社員番号:1、社員名:Sato、部署名:Sales
社員番号:2、社員名:Suzuki、部署名:Development
社員番号:3、社員名:Takahashi、部署名:Sales

補足:構造体配列の初期化

  • @angel_p_57 さんのコメントによると、以下のように構造体配列を初期化することもできるそうです。
  • 実際に書いてみたところ、2番目の書き方の方がシンプルですが、1番目の書き方の方が間違いが無さそうです。
emplistの初期化(その1)
    Employee empList[]={
        { .id=1, .name="Sato", .deptName="Sales", },
        { .id=2, .name="Suzuki", .deptName="Development", },
        { .id=3, .name="Takahashi", .deptName="Sales", },
    };
emplistの初期化(その2)
    Employee empList[]={
        { 1, "Sato", "Sales", },
        { 2, "Suzuki", "Development", },
        { 3, "Takahashi", "Sales", },
    };

参考URL

0
1
8

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
0
1