C语言——结构体、typedef、联合体(共用体)、枚举类型

一.结构体

作用:组合不同类型的数据。

声明语法:

struct 结构体名称    //结构体名称通常第一个名称为大写。
{
   结构体成员1;
   结构体成员2;
   结构体成员3;
   结构体成员4;
};

定义语法:

struct 结构体名称 结构体变量名;

也可以在声明时定义,看下后例子

 访问结构体变量:点号运算符(.)

例:

//书籍录入系统
#include <stdio.h>

struct Book		//声明有这样一个结构体
{
	char title[128];
	char author[40];
	float price;
	unsigned int date;
	char publisher[40];
} book1;//定义个全局变量的结构体book1

int main(void)
{
	struct Book book;//定义局部变量结构体book

	printf("请输入书名:");
	scanf("%s", book.title);//访问结构体变量
	getchar();
	printf("请输入作者:");
	scanf("%s", book.author);
	getchar();
	printf("请输入售价:");
	scanf("%f", &book.price);		//字符串不用取地址,而数需要&
	getchar();
	printf("请输入出版日期:");
	scanf("%d", &book.date);
	getchar();
	printf("请输入出版社:");
	scanf("%s", book.publisher);
	getchar();

	printf("=========数据录入完毕==========\n");
	printf("书名:%s\n", book.title);
	printf("作者:%s\n", book.author);
	printf("售价:%.2f\n", book.price);
	printf("出版日期:%u\n", book.date); 
	printf("出版社:%s\n", book.publisher);

	getchar();	//putchar()输出单个字符、getchar()过滤回车符
	return 0;
}

初始化结构体变量:(注意结构体的成员类型要一致)

struct Book book =
{
	"《C Primer Plus》",
	"Stephen P rata",
	60.00,
	20052,
	"人民邮电出版社"
};

初始化结构体指定成员值:(也可以在定义时初始化。)

struct Book book ={.price = 60.00}

注:这样写可以不按结构体声明的成员顺序初始化。

####编译器会对结构体成员进行内存对齐####对齐后做的微调节省空间

例:

#include <stdio.h>

struct A
{
	char a;
	int b;
	char c;
} a = {'x', 520, 'o'};//定义并初始化

int main(void)
{
	printf("size of a = %d\n", sizeof(a));
	
	getchar();
	return 0;
}

结果:

size of a = 12

微调:

#include <stdio.h>

struct A
{
	char a;
	char c;
	int b;
} a = {'x', 'o', 520};//定义并初始化

int main(void)
{
	printf("size of a = %d\n", sizeof(a));
	
	getchar();
	return 0;
}

结果:

size of a = 8

图解:

 

结构体嵌套:

例:

//书籍系统
#include <stdio.h>

struct Date
{
	int year;
	int month;
	int day;
}date;

struct Book		//声明有这样一个结构体
{
	char title[128];
	char author[40];
	float price;
	struct Date date;//结构体嵌套
	char publisher[40];
} book = {
	"《C Primer Plus》",
	"Stephen P rata",
	60.00
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值