不得不知道的结构体变量的定义和初始化方法

对于结构体,想必大多数人,会是喜欢,煎熬吧!!毕竟最难的C语言实现的通讯录,主要就是用了结构体,所以,结构体的重要性,不言而喻!!下面,想要知道:结构体变量的定义和初始化的各老铁,请紧跟笔者思路!!

1.创建变量的同时给初始化!

请看笔者的代码:

struct book
{
	char book_name[20];
	char author[20];
	int price;
	char id[5];
}sb3 = { "C语言程序设计","杜老师",88,"PG101" };
//定义的是全局变量!!

2.在main 函数里面局部变量初始化!


#include <stdio.h>

struct book
{
	char book_name[20];
	char author[20];
	int price;
	char id[5];
}sb3 = { "C语言程序设计","杜老师",88,"d101" };
//定义的是全局变量!!

int main()
{
	struct book sb1 = { "java虚拟机","赵老师",100,"z101" };
	//局部变量初始化
}

而打印过程需要:

	printf("%s %s %d %s\n", sb1.book_name, sb1.author, sb1.price, sb1.id);

所以,代码的运行结果为:

 而,结构体里面嵌套结构体变量也是可以的!!

下面,笔者来带领大家,走进,结构体的嵌套使用部分!!


#include <stdio.h>

struct stu
{
	char name[20];
	int age;
	char id[12];
};

struct book
{
	char book_name[20];
	char author[20];
	int price;
	char id[5];
	struct stu s;
}sb3 = { "C语言程序设计","杜老师",88,"d101",{"list",30,"20221009"} };
//定义的是全局变量!!

int main()
{

	printf("%s %s %d %s %s %d %s\n", sb3.book_name, sb3.author, sb3.price, sb3.id, sb3.s.name, sb3.s.age, sb3.s.id);

	return 0;
}

上面的代码中,笔者使用了结构体的嵌套使用:首先,定义了一个: struct book   的结构体,我们在这个结构体里面,嵌套了:struct stu s;  的结构体!!从而在打印的过程,需要:sb3.book_name, sb3.author, sb3.price, sb3.id, sb3.s.name, sb3.s.age, sb3.s.id,对于,这个不同,主要在于,嵌套的结构体struct stu s需要:先借用strucct book来找到struct stu s  ,从而找到name,age,id 等变量!!

从而最后的打印结果为:

 但是,对于两个结构体互相嵌套使用的情况下(你中有我,我中有你)怎样计算结构体的大小呢???很难吧!!所以,很少有着结构体互相嵌套使用的情况!(注意,这里说的是互相嵌套使用,不是嵌套使用)!!

但是对于结构体,我们也可以哎初始化的情况下:专门/指定初始化!

请看笔者代码:

#include <stdio.h>

struct s
{
	char c;
	int a;
	float b;
};

int main()
{
	//平常的初始化情况
	struct s s1 = { 'w',10,3.14 };
	printf("%c %d %f\n", s1.c, s1.a, s1.b);

	//专门/指定初始化!
	struct s s2 = { .b = 3.14,.c = 'w',.a = 10 };
	printf("%c %d %f\n", s2.c, s2.a, s2.b);

	return 0;
}

上述代码中:

	//专门/指定初始化!
	struct s s2 = { .b = 3.14,.c = 'w',.a = 10 };
	printf("%c %d %f\n", s2.c, s2.a, s2.b);

就是:专门/指定初始化了!!

代码的运行结果为:

上面的两种初始化所运行的结果都是一样的,所以,结构体也可以专门/指定初始化!!

猜你喜欢

转载自blog.csdn.net/weixin_64308540/article/details/127227421
今日推荐