0
0

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 1 year has passed since last update.

C言語の構造体

0
Posted at

構造体の基本的な定義

#include <stdio.h>

// 構造体の定義
struct Person {
    char name[50];  // 名前(文字列)
    int age;        // 年齢(整数)
    float height;   // 身長(小数)
};

int main() {
    // 構造体変数の宣言
    struct Person person1;

    // 値の代入
    person1.age = 25;
    person1.height = 170.5;
    strcpy(person1.name, "Taro");

    // 値の表示
    printf("名前: %s\n", person1.name);
    printf("年齢: %d\n", person1.age);
    printf("身長: %.1f cm\n", person1.height);

    return 0;
}

もっと便利に使う

構造体の配列

struct Person people[2] = {
    {"Alice", 30, 160.2},
    {"Bob", 28, 175.3}
};

printf("2人目の名前: %s\n", people[1].name); // Bob

構造体ポインタ

struct Person *p = &person1;
printf("ポインタ経由の年齢: %d\n", p->age);  // p->age は (*p).age と同じ

typedefで定義を短縮

typedef struct {
    char name[50];
    int age;
    float height;
} Person;

Person person2 = {"Ken", 22, 168.4};
0
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?