结构体
1.访问结构字段,点表示法,用 . 运算符
2.typedef为结构创建别名,用typedef定义结构时可以省略结构名
例如:
1 typedef struct cell_phone 2 { 3 int cell_no; 4 const char *wallpaper; 5 float minutes_of_charge; 6 }phone;// struct cell_phone是结构名,phone是类型名(别名),有了别名可以不写结构名 7 phone p = {5557879,"s.png",1.35};
3.想把结构传给函数并在函数中更新他的值,需要使用结构指针
4.(*t).age = t->age 才有效
*t.age = *(t.age) 并无实际意义
练习一:结构体
1 #include <stdio.h> 2 3 struct exercise 4 { 5 const char *description; 6 float duration; 7 }; 8 struct meal 9 { 10 const char *ingredient; 11 float weight; 12 }; 13 struct preferences 14 { 15 struct meal food;//结构体中的结构 struct meal 是新结构体,food是名称 16 struct exercise exercise; 17 }; 18 19 20 struct fish 21 { 22 const char *name;//注意定义字符串的两种方法 23 const char species[20]; 24 int teeth; 25 int age; 26 struct preferences care; 27 };//定义结构体后记得加分号 28 29 void catalog(struct fish f) 30 { 31 printf("%s is a %s with %i teeth. He is %i\n",f.name,f.species,f.teeth,f.age); 32 } 33 void label(struct fish f) 34 { 35 printf("Name:%s\n Species:%s\n %i years old,%i teeth\n",f.name,f.species,f.teeth,f.age); 36 printf("Feed with %2.2f lbs of %s and allow to %s for %2.2f hours\n", 37 f.care.food.weight,f.care.food.ingredient, 38 f.care.exercise.description,f.care.exercise.duration); 39 } 40 41 int main() 42 { 43 struct fish snappy = {"Snappy","Piranha",69,4,{{"meat",0.2},{"swim in the jacuzzi",7.5}} }; 44 catalog(snappy); 45 label(snappy); 46 return 0; 47 }
练习二:typedef的运用
#include <stdio.h> typedef struct { float tank_capacity; int tank_psi; const char *suit_material; }equipment; typedef struct scuba { const char *name; equipment kit; }driver; void badge(driver d) { printf("Name:%s Tank:%2.2f(%i) Suit:%s\n",d.name,d.kit.tank_capacity,d.kit.tank_psi,d.kit.suit_material); } int main() { driver randy = {"Randy",{5.5,3500,"Neoprene"}}; badge(randy); return 0; }
练习三:
1 #include <stdio.h> 2 3 typedef struct 4 { 5 const char *name; 6 const char *special; 7 int age; 8 }turtle; 9 10 void happy_birthday(turtle *t) 11 { 12 (*t).age = (*t).age + 1;//注意一定要加(),(*t).age = t -> age 13 printf("Happy birthday %s! You are now %i years old!\n",(*t).name,(*t).age); 14 } 15 int main() 16 { 17 turtle myrtle = {"Myrtle","Leatherback sea turtle",99}; 18 happy_birthday(&myrtle); 19 printf("%s's age is now %i\n",myrtle.name,myrtle.age); 20 return 0; 21 }