C语言---结构体详细介绍

最近在学习数据结构,趁机复习下C语言中的结构体
结构体的定义:
由于数组中只能存放同一类型的数据,所以c语言就规定把一些具有内在联系的不同数据类型的数据组合起来形成组合型的数据结构称为结构体。
声明一个结构体类型的一般形式为:

  struct   结构体名

         {成员表列};

结构体变量赋值的几种形式:

  1. 先声明结构体类型,再定义该类型的变量
  2. 在声明类型的同时定义变量
  3. 不指定类型名而直接定义结构体类型变量

/*
	与Java中的类,类似,对成员的访问,修改等
*/

# include <stdio.h>
# include <string.h>
struct Student
{
	int id_number;
	char name[200];
	int age;
};

void change_struct(struct Student *pst);
void put_struct(struct Student st);
void put_struct2(struct Student *pst);

int main(void)
{
	struct Student st = {100,"张三",12};//整体对结构体进行赋值
	printf("%d,  %s,  %d\n",st.id_number,st.name,st.age);
	printf("**************************************\n");

	st.age = 15;
	st.id_number = 120;
	//st.name = "lisi"; error C语言中不能对字符串进行赋值,要通过一个函数实现
	strcpy(st.name,"李四");
	printf("%d,  %s,  %d\n",st.id_number,st.name,st.age);
	printf("**************************************\n");

	change_struct(&st);
	printf("%d,  %s,  %d\n",st.id_number,st.name,st.age);
	printf("**************************************\n");

	put_struct(st);
	printf("**************************************\n");

	put_struct2(&st);
	printf("**************************************\n");

	return 0;
}

void change_struct(struct Student *pst)
{
	(*pst).age = 13;
	pst->id_number = 123;
	strcpy(pst->name,"王五");
}

//输出方式不推荐 较占内存 运行速度慢
void put_struct(struct Student st)
{
	printf("%d,  %s,  %d\n",st.id_number,st.name,st.age);
}

//
void put_struct2(struct Student *pst)
{
	printf("%d,  %s,  %d\n",pst->age, pst->name, pst->id_number);
}
/*
100,  张三,  12
**************************************
120,  李四,  15
**************************************
123,  王五,  13
**************************************
123,  王五,  13
**************************************
13,  王五,  123
**************************************
请按任意键继续. . .

*/
发布了16 篇原创文章 · 获赞 73 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_41948771/article/details/104442700