Skip to main content

Posts

Showing posts from October, 2014

All about structs

關於Heading first C的心得筆記,還有改編書中的範例當練習。 擁有多種型別成員的struct 在撰寫程式時會發現,我們常會利用相同片段的資料來處理不同的事,如下範例: /* Print out the personal informaion */ void personal_info( const char *name, const char *sick_type, float days, int age){ printf ( "%s got %s for %.1f days. She/he is %d.\n" , name, sick_type, days, age); } /* Print the label for the document */ void label( const char *name, const char *sick_type, float days, int age){ printf ( "Name: %s\nType of sick: %s, %.1f days\nAge: %d\n" , name, sick_type, days, age); } /* const char*: 將傳入一字串的指標,而非字串值,並且無法改動指向位址上的數值 */ /* 若想以字串的方式傳入,則將型別定義為char array,如char[20]即可 */ 當實際使用函數時,我們的程式碼將得重複輸入相同的4個參數,使得程式碼顯得有些凌亂,如下面這樣: int main(){ personal_info( "John" , "fever" , 3.5 , 23 ); label( "John" , "fever" , 3.5 , 23 ); return 0 ; } 但是其實兩段函數的輸入參數,都是屬於同一位病人所擁有的資料片段,然而由於這些資料片段並不一定為相同型別,因此僅能放入單一型別變數的Array將無法滿足我們的使用情境,此時可以考慮使用struct結構來將這些變數