温馨提示×

c语言怎么使用指针来访问结构体成员

小亿
114
2024-03-02 13:56:28
栏目: 编程语言

要使用指针来访问结构体成员,首先需要定义一个结构体,并创建一个指向该结构体的指针。然后通过该指针来访问结构体的成员。

以下是一个简单的示例:

#include <stdio.h>

// 定义结构体
struct Student {
    char name[50];
    int age;
};

int main() {
    // 创建一个结构体变量
    struct Student student1 = {"Alice", 20};
    
    // 创建一个指向结构体的指针
    struct Student *ptr = &student1;
    
    // 使用指针访问结构体成员并打印
    printf("Student name: %s\n", ptr->name);
    printf("Student age: %d\n", ptr->age);
    
    return 0;
}

在上面的示例中,首先定义了一个结构体Student,然后创建了一个结构体变量student1,并初始化了成员的值。接着创建一个指向该结构体的指针ptr,通过->操作符来访问结构体成员,最后打印了结构体成员的值。

0