C语言:结构体与结构体指针

1.结构体简介

比如C语言的 数组 允许定义可存储相同类型数据项的变量,结构体是 C 编程中另一种用户自定义的可用的数据类型,它允许您存储不同类型的数据项。

结构体中的数据成员可以是基本数据类型(如 int、float、char 等),也可以是其他结构体类型、指针类型等。

2.结构体类型

struct 结构体名字{

成员表列

} 变量;

(1)

cpp 复制代码
//定义了一个结构体有标题Books,有定义的变量book
//将结构体里面的成员引用且赋值
struct Books
{
	char title[50];
	char author[50];
	char subject[100];
	int book_id;
} book;
int main()
{
	strcpy_s(book.title, "钢铁是怎样炼成的");
	strcpy_s(book.author, "小明");
	strcpy_s(book.subject, "文学");
	book.book_id = 0;
	printf("书名:%s\n", book.title);
	printf("作者:%s\n", book.author);
	printf("学科:%s\n", book.subject);
	printf("编号:%d\n", book.book_id);
	return 0;
}

/**********另外一种赋值方式
int main()
{
	book.title[0] = 1;
	book.author[0] = 2; 
	book.subject[0] = 3;
	book.book_id = 4;
	printf("书名:%d\n", book.title[0]);
	printf("作者:%d\n", book.author[0]);
	printf("学科:%d\n", book.subject[0]);
	printf("编号:%d\n", book.book_id);
	return 0;
}
*/

(2)

cpp 复制代码
//定义了一个结构体无标题,有定义的变量s1,
// 这样这个结构体要定义其他成员的话,又要再写一遍,麻烦
//将结构体里面的成员引用且赋值
struct
{
	int a;
	char b;
	double c;
} s1;
int main()
{
	s1.a = 1;
	s1.b = 2;
	s1.c = 3;
	printf("%d\n", s1.a);
	printf("%d\n", s1.b);
	printf("%f\n", s1.c);
	return 0;
}

(3)

cpp 复制代码
//定义了一个结构体有标题,无定义的变量,需要单独在声明变量
//将结构体里面的成员引用且赋值
struct SIMPLE
{
	int a;
	char b;
	double c;
};
struct SIMPLE index;
int main()
{
	index.a = 1;
	index.b = 2;
	index.c = 3;

	printf("%d\n", index.a);
	printf("%d\n", index.b);
	printf("%f\n", index.c);
	return 0;
}

(4)

cpp 复制代码
//也可以用typedef创建新类型;typedef好处就是好看
typedef struct
{
	int a;
	char b;
	double c;
} Simple2;
//现在可以用Simple2作为类型声明新的结构体变量
 Simple2 index , u2[20] , *u3;
int main()
{
	index.a = 1;
	index.b = 2;
	index.c = 3;

	printf("%d\n", index.a);
	printf("%d\n", index.b);
	printf("%f\n", index.c);

	u2[0].a = 4;
	u2[0].b = 5;
	u2[0].c = 6;

	printf("%d\n", u2[0].a);
	printf("%d\n", u2[0].b);
	printf("%f\n", u2[0].c);

	u3 = &index;
	u3->a = 10;
	u3->b = 20;
	u3->c = 30;
	//用结构体指针访问结构体变量成员的第一种形式
	printf("%d\n", u3->a);
	printf("%d\n", u3->b);
	printf("%f\n", u3->c);
	//用结构体指针访问结构体变量成员的第二种形式
	printf("%d\n", (*u3).a);
	printf("%d\n", (*u3).b);
	printf("%f\n", (*u3).c);

	//已经改变指向结构体成员的数据了
	printf("%d\n", index.a);
	printf("%d\n", index.b);
	printf("%f\n", index.c);

	return 0;
}

注:内容参考C 结构体 | 菜鸟教程 (runoob.com)

相关推荐
卑微求AC2 小时前
(C语言贪吃蛇)11.贪吃蛇方向移动和刷新界面一起实现面临的问题
c语言·开发语言
冷静 包容3 小时前
C语言学习之 没有重复项数字的全排列
c语言·开发语言·学习
ROBIN__dyc3 小时前
C语言基本概念
c语言·开发语言
不穿格子衬衫13 小时前
常用排序算法(下)
c语言·开发语言·数据结构·算法·排序算法·八大排序
aqua353574235813 小时前
蓝桥杯-财务管理
java·c语言·数据结构·算法
Word码14 小时前
数据结构:栈和队列
c语言·开发语言·数据结构·经验分享·笔记·算法
五花肉村长14 小时前
数据结构-队列
c语言·开发语言·数据结构·算法·visualstudio·编辑器
qinzechen14 小时前
分享几个做题网站------学习网------工具网;
java·c语言·c++·python·c#
yttandb16 小时前
重生到现代之从零开始的C语言生活》—— 内存的存储
c语言·开发语言·生活
结衣结衣.16 小时前
python中的函数介绍
java·c语言·开发语言·前端·笔记·python·学习