结构体成员访问
在 C 语言中,.
和 ->
运算符的使用场景有明确区分,具体规则如下:
核心区别
运算符 | 操作对象类型 | 等价形式 | 应用场景 |
---|---|---|---|
. | 结构体变量 | 直接访问 | 结构体实例.成员 |
-> | 结构体指针 | (*指针).成员 | 结构体指针->成员 |
具体使用场景
1. 结构体变量用 .
struct Student {
char name[20];
int age;
};
// 声明结构体变量
struct Student stu;
// 访问成员
strcpy(stu.name, "张三");
stu.age = 18;
2. 结构体指针用 ->
// 声明结构体指针
struct Student *pStu = &stu;
// 访问成员
printf("%s", pStu->name); // 等效于 (*pStu).name
pStu->age = 20;
3. 混合使用场景(嵌套结构体)
struct Date {
int year;
int month;
};
struct Employee {
char name[20];
struct Date birthday;
struct Employee *manager;
};
// 结构体实例
struct Employee emp1 = {"李四", {1990, 7}};
// 结构体指针
struct Employee *pEmp = &emp1;
// 混合访问
printf("出生年份:%d", emp1.birthday.year); // 实例.成员.子成员
printf("主管姓名:%s", pEmp->manager->name); // 指针->指针成员->成员
4. 动态内存分配必须用 ->
struct Student *newStudent = malloc(sizeof(struct Student));
newStudent->age = 22; // ✅ 正确
// newStudent.age = 22; // ❌ 编译错误(newStudent 是指针)
常见错误示例
struct Book book;
struct Book *pBook = &book;
// 错误:对指针使用 .
pBook.price = 39.9; // ❌ 应改为 pBook->price
// 错误:对变量使用 ->
book->title = "C语言"; // ❌ 应改为 book.title
记忆口诀
点变量,箭头指,类型匹配要牢记
当操作对象是结构体实例时用 .
,是指针时用 ->
。这个规则同样适用于 C++ 的类和对象指针。