简单的结构体定义及练习
/* 《嗨翻C语言》随书练习 5章 结构 2016-12-04 xiousheng@126.com */ #include <stdio.h> //定义简单的结构体 struct turtle{ const char *name; const char *species; int age; } ; void happy_birthday(turtle t){ t.age += 1; printf("Happy Birthday %s!You are now %i years old!\r\n",t.name,t.age); } ; //结构体传参是用的复制数据,要改变结构体数据必须传指针 void happy_birthday1(turtle *t){ (*t).age += 1; printf("Happy Birthday %s!You are now %i years old!\r\n",(*t).name,(*t).age); //注意t->age 就是(.t).age ,是为了好看 } ; //保险箱窃贼 要组合得到字符串"GOLD" //结构体重命名 typedef struct{ const char *description; float value; } swag; typedef struct{ swag *pswag; const char *sequence; } combination; typedef struct{ combination numbers; const char *make; } safe; //保险箱窃贼例子函数实现 int baoxian(){ swag gold = {"GOLD",10000000.0}; combination numbers = {&gold,"6502"}; safe s = {numbers,"RAMACO250"}; printf("密码description是%s\r\n",s.numbers.pswag-> description); return 0; } int main(){ turtle myrtle = {"Myrtle","Leatherback sea turtle" ,99}; //结构体传参是用的复制数据 happy_birthday(myrtle); printf("%ss age is now %i\n",myrtle.name,myrtle.age); //看上面代码并没有改变结构体的数据 //必须传指针才行 happy_birthday1(&myrtle); printf("%ss age is now %i\n",myrtle.name,myrtle.age); baoxian(); return 0; }
联合体
/* 《嗨翻C语言》随书练习 5章 联合 2016-12-04 xiousheng@126.com 联合体应用场景,比如记录多个单位的数值,而单位是不定的,如斤,两等 */ #include <stdio.h> //定义简单的联合体 //union 是定义联合体的关键字 typedef union{ short count; float weight; float volume; } quantity; //联合体赋值,注意用{}默认的是表示第一个联合体字段的只 //其余的用.名字 = 值 的表示法。 //注意,联合体只能保存一条数据 //联合一般和结构一起用 typedef struct{ const char *name; const char *country; quantity amount; } fruit_order; //创建枚举记录联合体里保存的值 //定义枚举,enum为枚举关键字 ,枚举型用逗号分隔数据 typedef enum{ COUNT,POUNDS,PINTS } unit_of_measure; typedef union { //定义联合体 short count; float weight; float volume ; } woquantity; typedef struct{ const char *name; const char *country; woquantity amount; unit_of_measure units; }fruit_order1; void display(fruit_order1 order){ printf("This order contains\r\n"); if(order.units == PINTS){ printf("%2.2f pints of %s\r\n",order.amount.volume,order.name); }else if(order.units == POUNDS){ printf("%2.2f lbs of %s\r\n",order.amount.weight,order.name); }else{ printf("%i %s\r\n",order.amount.count,order.name); } } int main(){ //联合例子 //fruit_order apples = {"apples","England", .amount.weight = 4.2}; //书上是这样定义的,但我的编译器不支持,改成下面的 fruit_order apples = {"apples","England"}; apples.amount.weight = 4.2 ; printf("This order contains %0.2f 1bs of %s\r\n",apples.amount.weight,apples.name); //枚举例子 //fruit_order1 apples1 = {"apples","England",.amount.count = 144,COUNT}; //问题处在 .amount.count = 144,我编译器不支持,如何改写 /*下面的结构体是在c++环境下不能编译的定义试验,能通过*/ fruit_order1 apples1; apples1.name = "apples" ; apples1.country = "England" ; apples1.amount.count = 144; apples1.units = COUNT ; //继续正常定义模式 fruit_order1 mylist = {"mylist","ni de ",.amount.weight = 17.6,POUNDS}; fruit_order1 mylist2 = {"mylist2","ni de 2",.amount.volume = 12.6,PINTS}; display(apples1); display(mylist); display(mylist2); return 0; }
知识点