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

   2025-02-15 5280
核心提示:在C语言中,使用结构体指针可以方便地操作结构体变量的成员。下面是一个简单的示例:#include stdio.h// 定义一个结构体struct S

在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,我们可以动态分配内存给结构体,并使用->操作符来访问结构体成员。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言