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)

相关推荐
mit6.8246 分钟前
[Nagios Core] 通知系统 | 事件代理 | NEB模块,事件,回调
c语言·开发语言
mit6.8247 分钟前
[Nagios Core] 事件调度 | 检查执行 | 插件与进程
c语言·开发语言·性能优化
刃神太酷啦1 小时前
C++ 多态详解:从概念到实现原理----《Hello C++ Wrold!》(14)--(C/C++)
java·c语言·c++·qt·算法·leetcode·面试
弱冠少年2 小时前
ESP-Timer入门(基于ESP-IDF-5.4)
c语言
mit6.8242 小时前
[Nagios Core] struct监控对象 | 配置.cfg加载为内存模型
c语言·开发语言
遇见尚硅谷19 小时前
C语言:游戏代码分享
c语言·开发语言·算法·游戏
Jess0720 小时前
归并排序递归法和非递归法的简单简单介绍
c语言·算法·排序算法
双叶83621 小时前
(C++)STL标准库(vector动态数组)(list列表)(set集合)(map键值对)相关对比,基础教程
c语言·开发语言·数据结构·c++·list
j_xxx404_1 天前
c语言:字符函数和字符串函数
c语言·开发语言
apocelipes1 天前
C23和C++26的#embed嵌入资源指南
c语言·c++·开发工具和环境·c23·c++26