C语言结构体指针 #

一、结构体指针定义 #

1.1 基本语法 #

c
struct Student {
    char name[20];
    int age;
};

struct Student* p;

1.2 初始化 #

c
Student stu = {"Alice", 20};
Student* p = &stu;

二、通过指针访问成员 #

2.1 箭头运算符 #

c
#include <stdio.h>

typedef struct {
    char name[20];
    int age;
} Student;

int main() {
    Student stu = {"Alice", 20};
    Student* p = &stu;
    
    printf("姓名: %s\n", p->name);
    printf("年龄: %d\n", p->age);
    return 0;
}

2.2 等价写法 #

c
p->name
(*p).name

三、动态分配结构体 #

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char name[20];
    int age;
} Student;

int main() {
    Student* p = (Student*)malloc(sizeof(Student));
    if (p != NULL) {
        strcpy(p->name, "Alice");
        p->age = 20;
        printf("%s: %d岁\n", p->name, p->age);
        free(p);
    }
    return 0;
}

四、总结 #

操作 语法
定义 Student* p;
初始化 p = &stu;
访问 p->成员

下一步,让我们学习联合与枚举!

最后更新:2026-03-26