今天写代码时突然遇到了这个问题,以前不曾探讨过多层嵌套结构体指针变量的访问,只知道结构体指针变量要访问其元素时应该用 -> 来访问,但对于结构体中嵌套有结构体的时候呢?
请看下面代码:
#include “stdio.h”
using namespace std;
typedef struct Struct_Score
{
int chinese;
int math;
int english;
}ST_Score;
typedef struct Struct_Student
{
char name[5];
int id;
ST_Score score;
}ST_Student;
void get_score(ST_Student *student)
{
student->id = 1;
student->score.chinese = 80;
student->score.math = 90;
student->score.english = 90;
}
int main()
{
ST_Student student;
get_score(&student);
printf(“student.id = %d\n”, student.id);
printf(“student.score.chinese = %d\n”, student.score.chinese);
printf(“student.score.math = %d\n”, student.score.math);
printf(“student.score.english = %d\n”, student.score.english);
return 0;
}
其输出结果为:
因此,对于嵌套的结构体,只要不是指针变量,还是应该使用 . 访问。
好吧,这么简单基础的问题。。。