结构体、共用体、枚举
结构体
数组允许存储相同类型的数据,而不同类型的数据可以通过结构体来存储。
-
声明
struct tag { member-list member-list member-list ... } variable-list ;
-
定义
//直接定义变量 struct { int a; char b; double c; } s1; //先声明再定义变量 struct SIMPLE { int a; char b; double c; }; struct SIMPLE t1; //声明同时定义变量 struct SIMPLE2 { int a; char b; double c; } Sim; //也可以用typedef创建新类型 typedef struct { int a; char b; double c; } Simple3; Simple3 u1, u2[20], *u3;
-
初始化
#include <stdio.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } book = {"C 语言", "RUNOOB", "编程语言", 123456}; int main() { printf("title : %s\nauthor: %s\nsubject: %s\nbook_id: %d\n", book.title, book.author, book.subject, book.book_id); }
-
访问方式
直接访问用
.
,间接访问用->
。printf( "Book 1 title : %s\n", Book.title); printf( "Book 1 author : %s\n", Book.author); printf( "Book 1 subject : %s\n", Book.subject); printf( "Book 1 book_id : %d\n", Book.book_id); printf( "Book title : %s\n", book->title); printf( "Book author : %s\n", book->author); printf( "Book subject : %s\n", book->subject); printf( "Book book_id : %d\n", book->book_id);
枚举
-
声明
enum 枚举名 {枚举元素1,枚举元素2,……};
-
定义
方式参考结构体。
-
举例
#include <stdio.h> enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN } day; int main() { // 遍历枚举元素 for (day = MON; day <= SUN; day++) { printf("枚举元素:%d \n", day); } }
-
控制存储
enum cnum : char // 加上 :char 则元素道是专 char 类型属 { c_one, c_two, c_three }; enum snum : short // 加上 :short 则元素是 short 类型 { s_one, s_two, s_three }; enum inum : int // 加上 :int 则元素是 int 类型 { i_one, i_two, i_three };
共用体
-
声明
union [union tag] { member definition; member definition; ... member definition; } [one or more union variables];
-
定义
参考上面
-
存储空间
正如其名,它里面包含的数据类型都共用一块存储空间。当成员长度不同时,分配给共用体的内存大小取决于它的最大成员长度。
#include <stdio.h> union Data { int i; double f; char c; }; int main( ) { union Data data; printf( "Memory: %d\n", sizeof(data)); return 0; }