C语言之结构体(一)

版权声明:转载请注明 https://blog.csdn.net/qq_34720818/article/details/87924711

C语言之结构体

一、概念
结构体也是一种数据类型罢了,只不过它是一种由程序员自己定义的数据类型。结构体既然是一种数据类型那么也可以像基本数据类型一样,定义结构体变量、结构体数组、结构体指针。

**结构体的定义示例:**定义一个person的结构体数据类型

struct person
{
	char name[12];
	int age;
	float height;
	float weight;
};//注意分号不要忘记了

二、结构体变量的定义
方法一、先定义结构体类型再定义结构体变量

struct person
{
	char name[12];
	int age;
	float height;
	float weight;
};//注意分号不要忘记了
struct person per,pers[6],*pPer;//定义了变量per,数组pers,指针pPer;

方法二、在定义结构体类型的同时定义结构体变量

struct person
{
	char name[12];
	int age;
	float height;
	float weight;
} per,pers[6],*pPer;//注意分号不要忘记了

方法三、省略结构体名,直接定义结构体变量

struct //省略了结构体名
{
	char name[12];
	int age;
	float height;
	float weight;
} per,pers[6],*pPer;//注意分号不要忘记了

三、结构体变量初始化

方法一

struct person
{
	char name[12];
	int age;
	float height;
	float weight;
};//注意分号不要忘记了

struct person per={"Mekeater",23,1.8,60};//初始化

方法二

struct person
{
	char name[12];
	int age;
	float height;
	float weight;
} per={"Mekeater",23,1.8,60};

三、结构体变量的引用赋值

1、单一结构体变量

struct person
{
	char name[12];
	int age;
	float height;
	float weight;
};//注意分号不要忘记了

struct person per;
//引用赋值
 strcpy(per.name,"Mekeater");
per.age=23;
per.height=1.8;
per.weight=60;

注意:“.”在所有的运算符中优先级最高
2、嵌套结构体变量

struct author
{
	char name[12];
	int age;
	float height;
	float weight;
};
struct book
{
	char title[20];
	float price;
	struct author auth;
};
scanf("%s %s %d %f %f",b.title,b.auth.name,b.auth.age,b.auth.height,b.auth.weight)

四、结构体数组

struct person
{
	char name[12];
	int age;
	float height;
	float weight;
};//注意分号不要忘记了

struct person perp[2]={{"Mekeater",23,1.8,60},{"Sunhy",20,1.79,60}};
for(int i=0;i<2;i++)
{
	gets(p[i].name);
	scanf("%d",p[i].age);
}

猜你喜欢

转载自blog.csdn.net/qq_34720818/article/details/87924711