在工作过程中会遇到结构体,可能会忘记如何遍历结构体数组,这是一个简单的例子:
void structArrayPtr()
{
// 定义一个结构体数组
struct Student studentArray[2] = {
{"William", 18},
{"Mark", 20}
};
// 如何遍历结构体数组
for( int i=0; i<2; i++ )
{
cout << "name: " << studentArray[i].name << ", age: " << studentArray[i].age << endl;
}
cout << "***********************" << endl;
// 定义一个结构体
struct Student student;
student.name = "monkey";
student.age = 22;
// 定义一个结构体指针
struct Student *stu_ptr = &student;
// 利用->符去访问结构体成员
cout << "name: " << stu_ptr->name << ", age: " << stu_ptr->age << endl;
cout << "***********************" << endl;
// 定义新的结构体指针指向结构体数组
Student *stu_ptr1 = studentArray;
// 利用结构体指针遍历结构体数组元素,依旧利用->符号去获取
for( int var=0; var<2; var++, stu_ptr1++ )
{
cout << "name: " << stu_ptr1->name << ", age: " << stu_ptr1->age << endl;
}
}