19.C++结构体数组、指针

结构体数组

作用:将自定义的结构体放入到数组中方便维护
语法:struct 结构体名 数组名[元素个数] = { { } , { } , { } } ;

示例:

#include <iostream>
#include <string>
using namespace std;
//创建一个学生的数据类型
struct student
{
    string name;
    int age;
    int score;
};
int main()
{
    //创建结构体数组、给结构体中的元素赋值
    struct student stu_arr[3] =
    {
        {"张三" , 18 , 88 },
        {"李四" , 19 , 99},
        {"王五" , 20 , 100}
    };
    //更改数组结构体中元素的值
    stu_arr[2].name = "老头";
    stu_arr[2].age = 80;
    stu_arr[2].score = 10;
    for (int i = 0; i < 3; i++)
    {
        cout << "姓名: " << stu_arr[i].name 
             << "年龄:" << stu_arr[i].age 
             << "成绩: " << stu_arr[i].score << endl;
    }
    return 0;
}

结构体指针

作用:通过指针访问结构体中的成员

  • 利用操作符 -> 可以通过结构体指针访问结构体中的成员
#include <iostream>
#include <string>
using namespace std;
//创建一个学生的数据类型
struct student
{
    string name;
    int age;
    int score;
};
int main()
{
    //1、创建学生的结构体变量
    struct student stu ={ "二逼",18 , 90 };
    //2、通过指针指向结构体变量
    struct student* p = &stu;
    //3、通过指针访问结构体变量中的数据
    //结构体指针用->访问结构体属性
    cout << "姓名:" << p->name << "年龄 :" << p->age << "成绩: " << p->score << endl;
    return 0;
}

注意: 结构体指针用->访问结构体属性

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。