11.c++ 结构体与结构体数组、结构体指针

#include <iostream>
#include <string>
using namespace std;

//定义结构体
struct Student {
	//定义成员列表

	string name;
	int age;
	int score;
};


int main() {

	//声明结构体变量 ,这里struct可以省略
	struct Student s1;
	//给s1属性赋值,通过 . 访问结构体变量中的属性
	s1.name = "张三";
	s1.age = 18;
	s1.score = 90;

	cout << "姓名:" << s1.name << "年龄:" << s1.age << "成绩:" << s1.score << endl;

	Student s2;
	s2.name = "李四";
	s2.age = 19;
	s2.score = 100;

	system("pause");
	return 0;
}
  • 结构体数组
#include <iostream>
#include <string>
using namespace std;

//定义结构体
struct Student {
	//定义成员列表

	string name;
	int age;
	int score;
};

int main() {

	//创建结构体数组
	struct Student stuArray[3] =
	{
		{"张三", 18, 100},
		{"李四", 20, 90},
		{"王五", 21, 80}
	};

	//给结构体数组中的元素赋值
	stuArray[2].name = "赵六";
	stuArray[2].age = 30;
	stuArray[2].score = 60;

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

	system("pause");
	return 0;

}
  • 结构体指针
#include <iostream>
#include <string>
using namespace std;

//定义结构体
struct Student {
	//定义成员列表

	string name;
	int age;
	int score;
};

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

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

	//通过指针访问结构体变量中的数据
	//通过结构体指针访问结构体中的属性需要用 -> 
	cout << "姓名:" << p->name << "年龄:" << p->age << "成绩:" << p->score << endl;

	system("pause");
	return 0;

}
posted @ 2025-07-05 16:08  little小新  阅读(17)  评论(0)    收藏  举报