结构体 — 结构体数组、结构体指针

  • 结构体数组

点击查看代码
#include<iostream>
#include<string> 

using namespace std;

//结构体数组
//1、定义结构体
struct Student
{
	//成员列表
	string name;

	int age;

	int score;

};

int main(){
	
//2、创建结构体数组
	struct Student stuArray[3] = 
	{
		{"张三", 18, 88},
		{"李四", 19, 89},
		{"王五", 20, 90}
	
	};

//3、给结构体数组中的元素赋值
	stuArray[0].name = "赵六";

//4、遍历结构体数组
	for(int i = 0; i < 3; i++)
	{
		cout << "姓名:" << stuArray[i].name 
			 << "  age = " << stuArray[i].age 
			 << "  score = " << stuArray[i].score << endl;
	}

	system("pause");

	return 0;
}

 

 

  • 结构体指针

注意:

(1)通过指针访问结构体变量中的数据(需要利用"->")

(2)如果是结构体变量,可以直接 s.name 来访问结构体变量中的数据

点击查看代码
#include<iostream>
#include<string> 

using namespace std;

//结构体指针
//定义结构体
struct Student
{
	//成员列表
	string name;

	int age;

	int score;

};

int main(){
	
	//创建学生结构体变量
	Student s = { "张三", 18, 88 };

	//通过指针指向结构体变量
	Student *p = &s;

	//通过指针访问结构体变量中的数据(如果是结构体变量,可以直接 s.name 来访问结构体变量中的数据)
	//通过结构体指针访问结构体中的属性,需要利用"->"
	cout << "name = " << p->name << endl;

	system("pause");

	return 0;
}

 

posted @ 2021-08-04 15:25  毋纵年华  阅读(166)  评论(0)    收藏  举报