C语言:结构体

一、结构体

1.概念

结构体是不同类型数据的集合,把这些数据称为结构体的成员。
结构体类型需要自己定义来说明结构体中具体由哪些类型的数据组成,所以结构体也是一种自定义类型。

2.如何定义结构体类型

语法格式:
struct<结构体标签>{
成员类型 成员名;
成员类型 成员名;
… … ;
成员类型 成员名;
};
例如:定义一个学生的类型

struct student{
	int sno;
	char name[20];
	float score;
};

3.如何定义结构体变量

1)常规定义方式(最常用)

struct student{
	int sno;
	char name[20];
	float score;
};
			
struct student  st;   //st为结构体变量
struct student  st1,st2;   //st1,st2为结构体变量

2)与类型同时定义方式

struct student{
	int sno;
	char name[20];
	float score;
}st1,st2; 			//st1,st2为结构体变量

3)直接定义方式(最不常用)

struct {
	int sno;
	char name[20];
	float score;
}st1,st2; 			//st1,st2为结构体变量

4.结构体变量的初始化

//与数组类似

1)完全初始化

struct student st = {1001,“Jack”,98.56};

2)部分初始化

struct student st1 = {1001,“jack”};
struct student st2 = {1001};

3)指定成员初始化

struct student st = {.name = “Jack”,98.56,sno = 1002};

5.赋值和打印

1)赋值

注意:
//与数组相似,结构体变量也不能整体赋值,例如:
struct student st ;
st = {1001,“Jack”,98.56}; //错误
//只能分别给结构体中的每一个成员赋值,例如:
st.sno = 1002 ;
strcpy(st.name,“Jack”);
st.score = 87.87;
//同类型结构体变量之间可以互相赋值,例如:
struct student st1 = {1001,“Jack”,98.56};
struct student st2;
st2 = st1; //相互赋值

2)打印

只能分别打印每一个成员,例如:
struct student st1 = {1001,“Jack”,98.56};
printf("%d %s %.2f\n",st.sno,st.name,st.score);

6.结构体数组

元素为结构体类型的数组称为结构体数组,例如:
struct student st[5] ; //st[0],st[1],st[2],st[3],st[4]都是结构体类型的变量。
例如:

#include <stdio.h>
#include <string.h>

//定义一个结构体类型
struct student{
	int sno;
	char name[20];
	float score;
};

int main(void)
{
	int n,i;

	printf("请输入学生人数:");
	scanf("%d",&n);
	struct student  st[n];

	for(i = 0; i < n; i++){
		printf("请输入一个学生的信息:");
		scanf("%d%s%f",&st[i].sno,st[i].name,&st[i].score);
	}   

	printf("学生的信息如下:\n");
	printf("-------------------------\n");
	printf("sno    name  score\n");
	printf("-------------------------\n");
	for(i = 0; i < n; i++){
		printf("%d %s %.2f\n",st[i].sno,st[i].name,st[i].score);
	}   
			
	return 0;
}

7.结构体指针

保存结构体变脸地址的指针变量称为结构体指针变量,简称结构体指针。
例如:定义一个结构体类型

struct student{
	int sno;
	char name[20];
	float score;
};

int main(void)
{
	struct student  st = {1001,"Jack",98.56};
	struct student * ps; 

	ps = &st;  //结构体指针保存结构体变量的地址

	printf("%d  %s  %.2f\n",st.sno,st.name,st.score);
	printf("%d  %s  %.2f\n",(*ps).sno,(*ps).name,(*ps).score);
	printf("%d  %s  %.2f\n",ps->sno,ps->name,ps->score);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sashimi69

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值