iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 12
0
Software Development

提神?看程式比喝咖啡更有效。系列 第 12

輕談:struct結構是多此一項嗎?[1]入門

新手而言,因為資料量有限,所以struct(結構)語法很少會用到
相同類型的資料不多,而且重複性不高時,使用struct會感覺有點over
但對於日後工作,struct可是每天要面對的事
因為它可以把大量變數封装,不論是查看、傳輸...也十分方便
舉個例子:

#include <stdio.h>
    char TOM_name[10]="TOM";   //名字 
    char TOM_country[10]="HK"; //國家 
    int TOM_age=15;            //年齡 
    double TOM_height=150.2;   //身高 
    double TOM_weight=58.5;    //體重 

    char SAM_name[10]="SAM";   //名字 
    char SAM_country[10]="TW"; //國家 
    int SAM_age=18;            //年齡 
    double SAM_height=168.5;   //身高 
    double SAM_weight=65.3;    //體重 
int main(void) {
    printf("man1: \t%s, \t%s, \t%d, \t%.1lf, \t%.1lf\n", TOM_name, TOM_country, TOM_age, TOM_height, TOM_weight);
    printf("man2: \t%s, \t%s, \t%d, \t%.1lf, \t%.1lf\n", SAM_name, SAM_country, SAM_age, SAM_height, SAM_weight);
    return 0;
}

https://ithelp.ithome.com.tw/upload/images/20171225/20107818xMoocZrdf3.png
這是使用變數方式來表示
我們可以看到宣告的資料都是名字、國家、年齡、身高、體重,等個人資料(成員變數)
每當需要輸入多一位個人資料時,使需要再重複多宣告一次各項成員變數
假釋今天我們需要輸入100個人的個人資料,就可能需要宣告500次。
因此struct就可以解決這個問題,同時也可以提升可讀性

我們來看看範例

#include <stdio.h>
#include <string.h>
struct People {
    char name[10];    //名字 
    char country[10]; //國家 
    int age;          //年齡 
    double height;    //身高 
    double weight;    //體重 
};

int main(void) {
    struct People man1 = {"TOM", "HK", 15, 150.2, 58.5};
    struct People man2 = {"SAM", "TW", 18, 168.5, 65.3};
    printf("man1: \t%s, \t%s, \t%d, \t%.1lf, \t%.1lf\n", man1.name, man1.country, man1.age, man1.height, man1.weight);
    printf("man2: \t%s, \t%s, \t%d, \t%.1lf, \t%.1lf\n", man2.name, man2.country, man2.age, man2.height, man2.weight);
    return 0;
}

https://ithelp.ithome.com.tw/upload/images/20171225/20107818X3XlLrCrPX.png

雖然兩種方式所輸出結果相同,但struct(結構)可讀性也比較高,而且對於日後延伸更多筆資料也較好。
除了使用struct People man2 = {"SAM", "TW", 18, 168.5, 65.3};,一次過把各項成員輸入外,更可以逐項輸入

    struct People man2;
    strcpy(man2.name, "SAM");
    strcpy(man2.country, "TW");
    man2.age = 18;
    man2.height = 168.5;
    man2.weight = 65.3;

因為當年上課沒認真,結構我也是最近才重新再讀一次
在業界中,程式可能經過幾十位工程師的修改,每一位新工程師接手時,面對大量變數會顯得很吃力
因為很常使用struct,把相同類型、重複性高的變數...包裝起來
感覺像是:我們買筆、尺,可以直接去文具店買,我們不需去各類生產商購買。
文具店就是把文具包裝起來,當我們需要文具時,就可以直接呼叫文具店。


上一篇
call by value很佔空間?
下一篇
[影像處理系列] 影像模糊化[1]
系列文
提神?看程式比喝咖啡更有效。30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言