结构体的定义与使用

 

1.为什么需要结构体:
    为了表示一些复杂的事物,而普通的基本类型无法满足,比如一个学生需要表示其姓名,年龄,学号。
    结构体是一个复合数据类型。

  


2.如何定义结构体:
	第一种:
		struct Student
		{
			int age;
			float score;
			char sex[5];
		};//分号不要忘

	第二种:
		struct Student
		{
			int age;
			float score;
			char sex[5];
		}stu1;//定义了一个结构体类型的(变量),注意区别前面有typedef

		**
		typedef struct Student
		{
			int age;
			float score;
			char sex[5];
		}stu1;//代表将结构体这个(类型名)重新命名为stu1,而没有定义变量;
	第三种:
		struct 
		{
			int age;
			float score;
			char sex[5];
		}stu1;
3.怎么使用结构体变量
	赋值和初始化
			struct Student
			{
				int age;
				float score;
				char sex[5];
			};
			int main()
			
			{
				//第一种
				struct Student st1 = {80, 99.9, "boy"};
				printf("%d  %f  %s  ",st1.age,st1.score,st1.sex);

				//第二种
				struct Student st2;
				st2.age = 80;
				st2.score = 99.9f;//在C语言中默认99.9是double类型,若想以float类型输出,写成99.9f;
				strcpy(st2.sex,"boy");//特别注意字符串赋值不能用st2.sex = boy;
				printf("%d  %f  %s  ",st2.age,st2.score,st2.sex);

				//第三种
				struct Student st3;
				struct Student *pst = &st3;
				pst->age = 88;
				pst->score = 99.9f;
				strcpy(pst->sex,"boy");
				printf("%d  %f  %s  ",st3->age,st3->score,st3->sex);
			}
			
			
	结构体变量的输入输出:
		
			//结构体变量输入必须发送变量st的地址,因为要改变值只能用指针
			void InputStudent(struct Student * pstu)
			{
				(*pstu). age = 10;
				strcpy(pstu->name,"xuwei");
				strcpy(pstu->sex,"boy");
			}
			//结构体变量输出可以发送地址也可直接输出,因为输出不需要改变值,所以指针可用可不用
			  但为了节省内存,提高运行速度,推荐发送地址
			void Out putStudent(struct Student ss)
			{
				printf("%d %c %s\n", ss. age, ss. sex, ss. name) ;
			}
			int main(void)
			{
				struct Student st;
				InputStudent (&st); //对结构体变量输入
				Out putStudent(st); //对结构体变量输出
				return 0;
			}
			

  结构体变量的运算:
            结构体变量之间不能加减乘除,但可以相互赋值,如: st1 = st2;是对的

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值