C語言的結構體是一種特殊的數據類型,或者稱之為高級的數據類型,我們常說的int,long,float,double都屬於基礎類型,基礎類型只能存儲類型一致的數據。而結構體則能夠存儲不同的類型,它能夠存儲int ,char ,long 的復合類型。下面是一個我用結構體寫的簡單的實例,使用結構體先構造一個book類型的結構體,可以存儲多個book類型的值,這個稱為結構體數組,代碼的第22行聲明了一個結構數組,顧名思義,結構數組是指能夠存放多個結構體類型的一種數組形式。
1 /** 2 該程序使用結構體構造了一個簡單的書籍結構體 3 主要是結構體數組的使用方法 4 */ 5 #include <stdio.h> 6 #define MAX_TITLE_SIZE 30 7 #define MAX_AUTHOR_SIZE 40 8 #define MAX_SIZE 2 9 //構造一個BOOK結構體,用於存放title,author,price 10 struct book 11 { 12 char title[MAX_TITLE_SIZE]; 13 char author[MAX_AUTHOR_SIZE]; 14 float price; 15 }; 16 int main() 17 { 18 //設置一個計數器,用來計數輸入的次數 19 int count=0; 20 //設置另外一個計數器,用來遍歷顯示輸入的book 21 int index=0; 22 struct book lib[MAX_SIZE]; 23 printf("Set Book Title \n"); 24 //對相關的參量進行數據輸入 25 while(count<MAX_SIZE&& 26 printf("title is:")&&gets(lib[count].title)!=NULL && lib[count].title[0]!='\n') 27 { 28 printf("SET Your AUthor : \t"); 29 gets(lib[count].author); 30 printf("SET BOOKS price: \t"); 31 scanf("%f",&lib[count].price); 32 count++; 33 //如果不為\n,就繼續下一次的數據輸入 34 while(getchar()!='\n') 35 { 36 continue; 37 } 38 39 if(count<MAX_SIZE) 40 { 41 printf("Enter to next LINE to set title\n"); 42 43 } 44 } 45 if(count>0) 46 { 47 printf("Here are book lists \n"); 48 //遍歷結構體數組 49 for(index=0;index<count;index++) 50 { 51 printf("The Title is %s And The Author is %s And price is %f \n" 52 ,lib[index].title,lib[index].author,lib[index].price); 53 } 54 } 55 return 0; 56 }
以下是代碼的運行結果