C语言结构体的访问有哪些方法
在C语言中,我们可使用以下两种方法来访问结构体的成员:
1. 使用点运算符(`.`):通过结构体变量后面随着成员名和点运算符(`.`),即`结构体变量名.成员名`的方式来访问结构体的成员。
structPerson{ charname[20]; intage; }; intmain(){ structPersonperson1; strcpy(person1.name,"John"); person1.age=25; printf("Name:%s ",person1.name); printf("Age:%d ",person1.age); return0; }
输出:
Name:John Age:25
2. 使用指针和箭头运算符(`->`):如果我们定义了一个指向结构体的指针,我们可使用箭头运算符(`->`)来访问结构体的成员。
structPerson{ charname[20]; intage; }; intmain(){ structPersonperson1; structPerson*ptr=&person1; strcpy(ptr->name,"John"); ptr->age=25; printf("Name:%s ",ptr->name); printf("Age:%d ",ptr->age); return0; }
输出:
Name:John Age:25
上述两种方法都可以用于访问结构体的成员,具体使用哪种方法取决于你的需求和代码结构。
TOP