C Structure Pointers: Access Members Easily

In order to access the members of a struct using pointers, first you need to define a struct and create a pointer to that struct. Then use that pointer to access the struct’s members.

Here is a straightforward example:

#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;
}

In the example above, a struct named Student is first defined. Then a struct variable student1 is created and its members are initialized. Next, a pointer ptr is created pointing to the struct, and the struct members are accessed using the -> operator. Finally, the values of the struct members are printed.

bannerAds