结构体笔记
发布日期:2021-11-20 10:17:34 浏览次数:13 分类:技术文章

本文共 2258 字,大约阅读时间需要 7 分钟。

结构体笔记

1.结构体:其实也是一种数据类型,但是是一种复杂的数据类型,把一些基本类型数据组合在一起形成的一个新的复合数据类型

2.定义结构体的形式:

第一种:(比较推荐)

struct student1	{
int age; float score; char sex; };

第二种:前面定义了结构体的名字,最后面又定义了结构体变量

struct student2	{
int age; float score; char sex; };st2

第三种:没有结构体的名字

struct 	{
int age; float score; char sex; };

3.如何使用结构体变量:

赋值和初始化
1定义的同时可以整体赋值
2如果定义完之后,只能单个的赋初值

#include "pch.h"#include 
struct student1{
int age; float score; char sex;};int main(){
struct student1 st={
80, 66.6, 'F' }; //定义的同时可以整体赋值 struct student1 st2; //单独定义,自己的小错误,老是忘记写结构体的名字 st2.age = 10; st2.score = 88; st2.sex = 'F';}

4.如何取出结构体变量中的每一个成员

1.结构体变量名.成员名
2.指针变量的方式: 指针名->成员名

#include "pch.h"#include 
//这只是定义了一个新的数据类型,并没有定义变量struct student1{
int age; float score; char sex;};int main(){
struct student1 st = {
80, 66.6, 'F' }; //定义的同时可以整体赋值 //struct student1 st2; //单独定义,自己的小错误,老是忘记写结构体的名字 //st2.age = 10; // //st2.score = 88; //st2.sex = 'F'; // 定义方式 st.age = 80;// 第一种方式 struct student1* pst = &st; // 第二种指针定义法(更常用) pst->age = 80; //pst->age在计算机内部会被转化成(*pst).age,没有为什么,这就是->的含义,这是一种硬性规定。 //所以pst->age等价于(*pst).age,也等价于st.age //pst->age的含义: pst所指向的那个结构体变量中的age成员。(重要) st.age = 66.6f;//66.6在c语言中默认是double类型,如果希望是float类型,则需要在数字后面加f或者F return 0;}

5.指针变量和结构体

#include "pch.h"#include 
//定义函数之前要先声明,刚才没声明,一直显示找不到标识符,注意!!!!!void InputStudent(struct student1 * pstu);void OutputStudent(struct student1 ss);struct student1{
int age; float score; char sex;}; ///最后的这个分号不能省略int main(){
struct student1 st; InputStudent(&st);//对结构体变量输入,必须发送st的地址 printf("%d %d\n", st.age, st.score);//对结构体的输出,可以发送st的地址也可以直接发送st的内容,但为了减少内存耗费,也为了提高执行速度,推荐发送地址 OutputStudent(st); return 0;}void InputStudent(struct student1 * pstu) {
(*pstu).age = 16; pstu->score = 66.6f; pstu->sex = 'F';}void OutputStudent(struct student1 ss) {
printf("%d %d\n", ss.age, ss.score);}

6.结构体嵌套结构体

//结构体中的成员可以是另一个结构体

//例如:每个老师辅导一个学员,一个老师的结构体中,记录一个学生的结构体

#include "pch.h"#include 
#include
using namespace std;struct student {
string name; int age; int score;};struct teacher {
int id; string name; struct student stu; };int main(){
teacher t; t.name = "nn"; t.stu.name = "oo";//嵌套}

转载地址:https://blog.csdn.net/weixin_43223362/article/details/101476945 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:switch-scanf-break-continue简单知识点
下一篇:指针笔记_4

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年03月30日 11时41分00秒