温馨提示×

c语言结构体指针怎么使用

小亿
87
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