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)

相关推荐
范纹杉想快点毕业11 分钟前
以项目的方式学QT开发C++(二)——超详细讲解(120000多字详细讲解,涵盖qt大量知识)逐步更新!
c语言·开发语言·c++·windows·vscode·qt·visual studio
少了一只鹅41 分钟前
c语言内存函数
c语言·开发语言
映秀小子1 小时前
C语言链表的操作
c语言·开发语言·链表
小辉懂编程8 小时前
C语言:51单片机实现数码管依次循环显示【1~F】课堂练习
c语言·开发语言·51单片机
Inverse16210 小时前
C语言_动态内存管理
c语言·数据结构·算法
whoarethenext12 小时前
c/c++的opencv的轮廓匹配初识
c语言·c++·opencv
apocelipes12 小时前
使用libdivide加速整数除法运算
c语言·c++·性能优化·linux编程
青出于兰13 小时前
C语言| 指针变量的定义
c语言·开发语言
思茂信息18 小时前
CST软件对OPERA&CST软件联合仿真汽车无线充电站对人体的影响
c语言·开发语言·人工智能·matlab·汽车·软件构建
川川菜鸟19 小时前
2025长三角数学建模C题完整思路
c语言·开发语言·数学建模