C言語の構造体ポインタの使い方

構造体ポインタを使って、構造体変数のメンバーに簡単にアクセスできます。以下にシンプルな例を紹介します。

#include <stdio.h>

// 定义一个结构体
struct Student {
    char name[20];
    int age;
    float score;
};

int main() {
    // 声明一个结构体指针变量
    struct Student *stuPtr;
  
    // 动态分配内存给结构体指针
    stuPtr = (struct Student*)malloc(sizeof(struct Student));
  
    // 通过结构体指针访问结构体成员
    strcpy(stuPtr->name, "Tom");
    stuPtr->age = 18;
    stuPtr->score = 95.5;
  
    // 打印结构体成员的值
    printf("Name: %s\n", stuPtr->name);
    printf("Age: %d\n", stuPtr->age);
    printf("Score: %.1f\n", stuPtr->score);
  
    // 释放内存
    free(stuPtr);

    return 0;
}

上記の例では、構造体のポインタ変数stuPtrを使って動的に構造体にメモリを割り当て、->演算子で構造体のメンバにアクセスすることができます。

bannerAds