结构体相关知识

目录

一. 什么是结构体,为什么需要结构体

二. 如何定义结构体

三. 如何去使用结构体变量

 1. 赋值和初始化

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

 3. 结构体变量和指针变量作为函数参数传递的问题

 4.结构体变量的运算        


一. 什么是结构体,为什么需要结构体

   把一些基本类型数据组合在一起形成一个新的复合数据类型,这个叫做结构体   

为了表示一些复杂的事物,而普通的基本类型无法满足实际需要


二. 如何定义结构体

 第一种 只是定义了一个新的数据类型,并没有定义变量

#include<stdio.h>
struct student 
{
	int age;
	float score;
	char sex;
};
int main(void)
{
	struct student st = { 80, 66.6, 'F' };
	return 0;
}

  第二种

#include<stdio.h>
struct student2
{
	int age;
	float score;
	char sex;
}st2;
int main(void)
{
	struct student st = { 80, 66.6, 'F' };
	return 0;
}

  第三种

#include<stdio.h>
struct 
{
	int age;
	float score;
	char sex;
}st3;
int main(void)
{
	struct student st = { 80, 66.6, 'F' };
	return 0;
}

三种方式 推荐第一种 


三. 如何去使用结构体变量

 1. 赋值和初始化

   定义的同时可以整体赋值。

   如果定义完之后,则只能单个的赋初值

#include<stdio.h>
struct student
{
	int age;
	float score;
	char sex;
};
int main(void)
{
	struct student st = { 80, 66.6, 'F' };//初始化 定义的同时赋初值
	struct student st2;
	st2.age = 10;
	st2.score = 88.8;
	st2.sex = 'F';

	printf("%d %f %c\n", st.age, st.score, st.sex);
	printf("%d %f %C\n", st2.age, st2.score, st2.sex);

	return 0;
}

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

 1.  结构体变量名.成员名

 2.  指针变量名->成员名  (更常用)

#include<stdio.h>
struct student
{
	int age;
	float score;
	char sex;
};
int main(void)
{
	struct student st = { 80, 66.6, 'F' };//初始化 定义的同时赋初值
	struct student * pst = &st;//$st不能改成st
	
	pst->age = 88;//第二种
	st.score = 66.6f;//第一种
	printf("%d %f\n", st.age, pst->score);

	return 0;
}
//66.6在C语言系统中默认为double类型,如果希望是float类型,则必须在末尾加f或F

       浮点数不能准确存储

1  pst->age  在计算机内部会被转化成  (*pst).age                                                                                  st.age  等价于 pst->age  等价于  (*pst).age

  2  我们之所以知道lpst->age等价于st,age,是因为pst->age是被转化成了(*pst).age来执行                    所以说这两种方式是等价的

  3   pst->age的含义:pst所指向的那个结构体变量中的age这个成员 


 3. 结构体变量和指针变量作为函数参数传递的问题

    推荐使用结构体指针变量作为函数参数来传递

*
  通过函数完成对结构体变量的输入和输出
*/
#include<stdio.h>
#include<string.h>

struct student
{
	int age;
	char sex; 
	char name[100];
};

void inputstudent(struct student * pstus);
void outputstudent(struct student ss);
int main(void)  
{
	struct student st;

	 inputstudent(&st);//对结构体变量输入  必须发送st的的地址
	// printf("%d %c %s\n", st.age, st.sex, st.name);
	 outputstudent(st);//对结构体变量输出  可以发送st的地址也i可以发送st的内容
	 
	 return 0;
}

void outputstudent(struct student ss)
{
	printf("%d %c %s\n", ss.age, ss.sex, ss.name);
}

void inputstudent(struct student * pstu)//pstu只占四个字节
{
	(*pstu).age = 10;
	strcpy_s(pstu->name, "龙少");
	pstu->sex = 'F';
}/* 10 F 龙少  */

 4.结构体变量的运算 

    结构体变量不能相加,不能相减,也不能相互乘除                                                                            但结构体变量可以相互赋值  

               

         

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值