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)

相关推荐
伊H2 小时前
C语言main的参数;argc与argv
linux·c语言·算法
暖阳冷月海无涯3 小时前
数据结构-C语言版本(一)数组
c语言·数据结构
Non importa4 小时前
【初阶数据结构】树——二叉树(上)
c语言·数据结构·学习·算法
汤姆_5116 小时前
【c语言】深度理解指针4——sizeof和strlen
c语言·开发语言
_GR6 小时前
2025年蓝桥杯第十六届C&C++大学B组真题及代码
c语言·数据结构·c++·算法·贪心算法·蓝桥杯·动态规划
照海19Gin8 小时前
数据结构中的宝藏秘籍之广义表
c语言·数据结构·算法
加点油。。。。8 小时前
C语言高频面试题——strcpy与memcpy区别
c语言·开发语言
双叶8368 小时前
(51单片机)LCD显示数据存储(DS1302时钟模块教学)(LCD1602教程)(独立按键教程)(延时函数教程)(I2C总线认识)(AT24C02认识)
c语言·数据库·单片机·嵌入式硬件·mongodb·51单片机·nosql
那就摆吧8 小时前
数据结构-栈
android·java·c语言·数据结构
L_09079 小时前
【C】初阶数据结构10 -- 希尔排序
c语言·数据结构·排序算法