C/C++结构体

目录

结构体的定义和使用

结构体数组

结构体指针

结构体传参


结构体的定义和使用

struct 结构体名{结构体成员列表};

上面我们设置好了一个结构体之后,然后我们可以创建结构体变量

一共有三种创建的方式

(1)struct 结构体名 变量名;

(2)struct 结构体名 变量名 = {成员1,成员2};

(3)定义结构体的时候顺便创建变量

#include <iostream>
#include<string>
using namespace std;
//1.创建学生结构体类型:学生(姓名,年龄,分数)
struct Student {
	string name;
	int age;
	int score;
}s3;
int main()
{
	//(1)struct Student s1;
	struct Student s1;//struct的关键字可以不写
	//给s1赋值,通过一个.来访问结构体变量的属性
	s1.name = "张三";
	s1.age = 18;
	s1.score = 100;
	//(2)struct Student s2={....}
	struct Student s2 = { "李四",19,80 };//struct的关键字可以不写
	//定义结构体的时候顺便就创建
	s3.name = "王五";
	s3.age = 19;
	s3.score = 10;
	return 0;
}
	

结构体数组

语法:struct 结构体名 数组名[元素个数] = {{} ,{}, {},{}};

#include <iostream>
#include<string>
using namespace std;
//1.创建学生结构体类型:学生(姓名,年龄,分数)
struct Student {
	string name;
	int age;
	int score;
};
int main()
{
	struct Student stuArray[3] =
	{
		{"张三",18,100},
		{"李四",29,100},
		{"王五",8,99}
	};
//改变数据
	stuArray[2].name = "赵六";
	stuArray[2].age = 80;
//遍历结构体数组
	for (int i = 0; i < 3; i++)
	{
		cout << "姓名 " << stuArray[i].name<<endl;
	}
	return 0;
}
	

结构体指针

#include <iostream>
#include<string>
using namespace std;
//1.创建学生结构体类型:学生(姓名,年龄,分数)
struct Student {
	string name;
	int age;
	int score;
};
int main()
{
	//1.创建一个结构体变量
	Student s = { "张三",18,100 };
	//2.通过指针指向结构体变量
	Student* p = &s;
	//3.通过指针访问结构体变量中的数据,用-->来访问属性
	cout << p->name << endl;
	return 0;
}

结构体传参

#include <iostream>
#include<string>
using namespace std;
//1.创建学生结构体类型:学生(姓名,年龄,分数)
struct Student {
	string name;
	int age;
	int score;
};
void printStudent1(Student s)
{
	s.name = 100;
	cout << s.name << s.age << s.score << endl;
}
void printStudent2(Student* s)
{
	s->age = 200;
	cout << s->age << endl;
}
int main()
{
	//1.创建一个结构体变量
	Student s = { "张三",18,100 };
	printStudent1(s);//值传递不能改变结构体中的值
	printStudent2(&s);//地址传递可以改变结构体中的值
	return 0;
}
	

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值