C语言-结构体

1.初识结构体

结构体的作用:放置变量的定义,使程序更加清晰明了;
结构体的使用:首先,要进行结构体内容的定义;然后,要进行结构体变量,指针或数组的定义;最后,对结构体变量,指针或数组进行初始化;
结构体的语法:struct (变量名)
        {结构体内容}变量、指针或数组名字或直接进行初始化;

2.简单结构体的使用

#include<stdio.h>
#include<string.h>
//定义结构体方法之一
//Student是结构体的名字
//大括号内部是结构体定义的内容
struct Student
{
	int age;
	char name[50];
	int score;
};

//这里定义结构体的同时直接定义全局的结构体变量Stu1和Stu2;
//在这里定义的结构体变量可以直接在主函数中使用;
//同时,可以在这里直接对结构体变量进行初始化操作;
struct Student1
{
	int age;
	char name[50];
	int score;
}Stu1,Stu2={18,"Tom",67};

//下面定义的是佚名结构体,在主函数中不可以进行结构体变量等的定义;
//仅仅只能用在这里直接定义的结构体变量;
struct
{
	int age;
	char name[50];
	int score;
}Stu0;
int main()
{	
	//定义结构体变量
	struct Student stu;
	//结构体变量的初始化
	stu.age=19;
	strcpy(stu.name,"Tom");
	stu.score=90;

	//定义结构体指针
	struct Student *p=&stu;
	//通过指针对变量进行赋值
	//这里的 -> 可以换成 .    p->age===>(*p).age
	p->age=18;
	strcpy(p->name,"Tom");
	p->score=78;

	//定义结构体数组
	struct Student s[2];
	//给结构体数组赋值
	s[2]=
	{
	{18,"Tom",77},
	{19,"Jim",99},
	{16,"Lily",66}
	}

	//打印学生信息
	printf("名字:%s \n年龄:%d \n成绩:%d \n",stu.name,stu.age,stu.score);
	return 0;
}

3.结构体的嵌套

#include<stdio.h>
#include<string.h>
//对嵌套的结构体进行定义
struct Info
{
	int age;
	char name[50];
};

struct Student
{
	struct Info info;
	int score
};

int main()
{
	struct Student s;
	//在这里需要注意不能直接用s.age,要加上嵌套的结构体s.info.age
	s.info.age=18;
	strcpy(s.info.name,"Tom");
	s.score=89;
	printf("%d,%s,%d\n",s.info.age,s.info.name,s.score);
	return 0;
}

4.union共同体

首先,共同体同结构体的语法规则是一样的;
其次,共同体的内存同共同体中的占用内存最大的变量大小相同;
最后,当对共同体中的某一个变量赋值,会对其他的变量产生影响。

#include<stdio.h>
#include<stdlib.h>
union Student
{
	char name[40];
	int age;
	int score;
};
int main()
{
	union Student S;
	S.age=0x18;
	S.score=0x2233;
	printf("%d,%s\n",S.age,S.score);
	return 0;
}

5.enum 枚举的使用

首先,枚举的结构同结构体相同;
其次,枚举的内部定义简单来说就是给一些特征贴上标签;

#include<stdio.h>
enum color
{
	//这里面的各个特征依次赋予标签0,1,2,3,10,11
	red,green,white,black,blue=10,light
};
int main()
{
	int col=1;
	if(col==red)
	{
		printf("red\n");
	}
	else if(col==green)
	{
		printf("green\n");
	}
	else
	{
		printf("Other!\n");
	}

	enum color tmp;
	tmp=red;	//给枚举变量tmp赋值为0
	return 0;
}

6.typedef 的使用

首先,typedef不能够定义新的变量类型;
其次,这个函数能够给变量类型定义一个附属的名字。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Student
{
	char name[20];
	int age;
	int score;
};
int main()
{
	typedef struct Student Stu;
	Stu s;
	s.age=18;
	s.score=99;
	strcpy(s.name,"Tom");
	printf("%s,%d,%d\n",s.name,s.age,a.name);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值