C语言学习笔记(五)--结构体、共用体、枚举

C语言学习笔记(五)

结构体:若干成员组成的数据类型

声明方式:

struct 结构体{

​ 数据类型 成员名;

​ 数据类型 成员名;

​ …

};

#include 
struct student{
	int num;
	char name[20];
	int age;
};
int main(){
	struct student stu;
	stu.name = "Xiao ming";
	stu.num = 1;
	stu.age = 18;
	printf("num = %d,name is %s,age = %d",stu.num,stu.name,stu.age);
}

结构体中内存对齐问题:例如在32位机中,如果某个类型的数据不能填满这4字节,那么下一个数据不会接着填充,而是会在下一段重新填充

struct student{
	int num;
	char name;
	int age;
};

这样的一个struct student类型的变量,在32位机中占12字节,而不是9字节

共用体(联合体):一种特殊的数据类型,一个共用体内可以定义多种不同的数据类型,这些数据共享一段内存,在同一时间只能存储其中一个成员变量的值

用共用体判断系统是大端还是小端

#include 
union test{
	int a;
	char c;
};
int main(){
	test t;
	t.c = 1;
	if(t.a == 0x0001)
		printf("little endian\n");
	else if(t.a == 0x1000)
		printf("big endian\n");
	else 
		printf("error\n");
	return 0;
}

枚举:在枚举类型中列出所有可能的值,枚举的变量取值不能超过定义的范围

enum 枚举类型名{枚举常量列表};

#include 
int main(){
	enum weather{sunny,cloudy,rainy,windy};
	//其中sunny = 0,cloudy = 1,rainy = 2,windy = 3
    printf("%d",cloudy);
	return 0;
}

你可能感兴趣的:(c语言,enum)