Linux C语言:C结构体及结构体数组

一、结构体的意义

问题:学籍管理需要每个学生的下列数据:学号、姓名、性别、年龄、分数,请用C语言程序存储并处理一组学生的学籍。

单个学生学籍的数据结构

  • 学号(num):int型
  • 姓名(name):char [ ] 型
  • 性别(sex):char型
  • 年龄(age):int型
  • 分数(score):float型

思考:如果有多个学生,该怎么定义已学数据类型无法解决。

二、结构体的概述

正式:结构体是由一批数据组合而成的结构型数据。组成结构型数据的每个数据称为结构型数据的“成员”   ,其描述了一块内存区间的大小及解释意义。

通俗:结构体属于用户自定义的数据类型,允许用户存储不同的数据类型

三、结构体的定义

语法:

struct  结构体名

{

  结构体成员列表

};

四、结构体的使用

struct  结构体名  变量名

struct  结构体名  变量名 = {成员1值,成员2值..}

定义结构体时顺便创建变量

#include <stdio.h>
#include <string.h>
 
//结构体的定义
struct student
{
	int num; //学号
	char name[16];  //姓名
	float score;  //成绩
}stu5 = {1002,"lihua",89},stu6;  //3.定义结构体时顺便定义变量
 
int main(int argc, const char *argv[])
{
 
	//1.定义完结构体变量再进行赋值
	struct student stu1;
 
	stu1.num = 1000;
	strcpy(stu1.name,"zhangsan");
	//stu1.name = "zhangsan";    //错误行为
	stu1.score = 98;
 
	printf("num = %d, name = %s, score = %f\n", stu1.num, stu1.name, stu1.score);
 
 
	//2.定义结构体变量时进行赋值
	struct student stu2 = {1001, "lisi", 99};
	
	printf("num = %d, name = %s, score = %f\n", stu2.num, stu2.name, stu2.score);
 
	struct student stu3 = {1001, "lisi"};
	printf("num = %d, name = %s, score = %f\n", stu3.num, stu3.name, stu3.score);
 
	struct student stu4 = {
		.num = 1001, 
		.score = 99,
	};
	printf("num = %d, name = %s, score = %f\n", stu4.num, stu4.name, stu4.score);
 
	printf("num = %d, name = %s, score = %f\n", stu5.num, stu5.name, stu5.score);
 
	stu6.num = 1004;
	strcpy(stu6.name,"zhangsan2");
	stu6.score = 70;
	printf("num = %d, name = %s, score = %f\n", stu6.num, stu6.name, stu6.score);
	return 0;
}

五、结构体数组

作用:将自定义的结构体放入到数组中方便维护

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

#include <stdio.h>
#include <string.h>
 
//定义结构体
struct student
{
	int num;
	char name[16];
	float score;
};
 
int main(int argc, const char *argv[])
{
	struct student stu[3] = {{1000, "zhangsan", 99}, {1001, "lisi", 89}, {1003, "zhouwu", 79}};
	struct student stu1[3];
	int i;
 
	stu1[0].num = 2000;
	strcpy(stu1[0].name, "lihua");
	stu1[0].score = 100;
 
	printf("num = %d, name = %s, score = %f\n", stu1[0].num, stu1[0].name, stu1[0].score);
 
	for (i = 0; i < 3; i++)
	{
		printf("num = %d, name = %s, score = %f\n", stu[i].num, stu[i].name, stu[i].score);
	}
 
	return 0;
}

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值