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 }