溫馨提示×

c語言結構體指針怎么使用

小億
127
2023-11-24 02:42:37
欄目: 編程語言

在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,我們可以動態分配內存給結構體,并使用->操作符來訪問結構體成員。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女