C语言学习014:结构化数据类型

struct的基本使用

 1 #include <stdio.h>
 2 
 3 //定义数据结构
 4 struct fish{  5     const char *name;  6     const char *species;  7     int teeth;  8     int age;  9 }; 10 
11 void catalog(struct fish f){ 12     printf("%s is a %s with %i teeth. He is %i\n",f.name,f.species,f.teeth,f.age);//访问结构的字段
13 } 14 
15 int main(){ 16     //声明结构变量
17     struct fish snappy={"Snappy","Piranha",69,4}; 18  catalog(snappy); 19     return 0; 20 }

  将结构变量赋值给另一个结构变量时,计算机会创建一个全新的结构副本,然后将每个字段都复制过去;如果结构中有指针,那么复制的仅仅是指针的值

struct fish snappy={"Snappy","Piranha",69,4}; struct fish gnasher=snappy;

  结构还可以嵌套使用

 1 #include <stdio.h>
 2 
 3 struct preferences{  4     const char *food;  5     float exercise_hours;  6 };  7 
 8 struct fish{  9     const char *name; 10     const char *species; 11     int teeth; 12     int age; 13     struct preferences care;//嵌套在fish中的结构体preferences
14 }; 15 
16 void catalog(struct fish f){ 17     printf("%s is a %s with %i teeth. He is %i\n",f.name,f.species,f.teeth,f.age);//访问结构的字段 18     //访问结构体中的结构体
19     printf("%s like to eat %s\n",f.name,f.care.food); 20     printf("%s like to exercise %f hours\n",f.name,f.care.exercise_hours); 21 } 22 
23 int main(){ 24     struct fish snappy={"Snappy","Piranha",69,4,{"Meat",7.5}}; 25  catalog(snappy); 26     return 0; 27 }

更简单的创建结构变量

  通过使用typedef为结构命名,这样在创建结构变量的时候可以省去struct关键字

#include <stdio.h> typedef struct cell_phone{ int cell_no; const char *wallpapaer; } phone;//phone为类型名(cell_phone的别名)

int main(){ phone p={5555,"sinatra.png"}; printf("number %i\n",p.cell_no); return 0; }

  我们还可以直接省去结构的名字定义结构,这也就是所谓的匿名结构

1 typedef struct { 2     int cell_no; 3     const char *wallpapaer; 4 } phone;

 传递结构指针

  当将一个结构赋值给另一个结构,我们知道是创建一个新的副本;如果我们希望通过被赋值的结构更新原来的结构,就需要用到结构指针

 1 #include <stdio.h>
 2 
 3 typedef struct {  4     int cell_no;  5     const char *wallpapaer;  6 } phone;  7 
 8 int main(){  9      phone p={5555,"sinatra.png"}; 10      phone p2=p; 11      p2.cell_no=4444; 12      printf("p.cell_no:%i p2.cell_no:%i\n",p.cell_no,p2.cell_no); 13      phone* p3=&p;//将结构p的地址赋值给*p3
14      (*p3).cell_no=6666; 15      printf("p.cell_no:%i p2.cell_no:%i p3.cell_no:%i\n",p.cell_no,p2.cell_no,(*p3).cell_no); 16     return 0; 17 }

  因为我们常常会把(*p2).wallpapaer错误的写成*p2.wallpapaer,它们并不等价,所以C语言开发者设计了更简单的表示结构指针的方法

1 int main(){ 2      phone p={5555,"sinatra.png"}; 3      phone* p2=&p; 4      printf("p2->wallpapaer:%s = (*p2).wallpapaer:%s\n",p2->wallpapaer,(*p2).wallpapaer);// 5     return 0; 6 }

你可能感兴趣的:(C语言学习014:结构化数据类型)