[英]C Language: Structure and Arrays
是否可以使現有結構成為一個數組?
struct violation v1={"AA1", "Defective_Brakes", 150};
struct violation v2={"AA2", "Disregarding_Traffic_Signs", 150};
struct violation v3={"AA3", "Driving_Under_the_Influence_of_Liquor", 2000};
struct violation v4={"AA4", "Driving_while_using_Mobile_Devices", 200};
struct violation v5={"AA5", "Drinving_without_License", 750};
struct violation v6={"AA6", "Driving_Against_Traffic", 2000};
struct violation v7={"AA7", "Failure_to_use_Seatbelt", 500};
struct violation v8={"AA8", "Illegal_Parking", 200};
struct violation v9={"AA9", "Overspeeding", 1200};
struct violation v10={"AA10", "Reckless_Driving", 750};
這應該是我的代碼的數據庫。 我想把它變成一個數組,使數據庫中的搜索更容易。 我能做什么?
數組是同源的,即它只能保存一次,就像數組中的所有元素都是整數或字符串一樣,但你不能混合你可以使用結構的類型,我在你的例子中看到你有String和Integer,因此如果你想將你的結構更改為數組,然后你必須將它們全部轉換為字符串。
另外考慮你的情況,我會建議你繼續使用結構,因為它混合了數據類型。 您還可以使用struct violation violations [n];
將所有這些struct存儲在數組中struct violation violations [n];
然后使用for循環來填充違規行為,請按照如何在C中創建結構數組? 完整的例子。
是。 就像您對常規數組所做的那樣,您可以創建一個struct
數組:
struct violation v[10]={
{"AA1", "Defective_Brakes", 150},
{"AA2", "Disregarding_Traffic_Signs", 150},
{"AA3", "Driving_Under_the_Influence_of_Liquor", 2000},
{"AA4", "Driving_while_using_Mobile_Devices", 200},
{"AA5", "Drinving_without_License", 750},
{"AA6", "Driving_Against_Traffic", 2000},
{"AA7", "Failure_to_use_Seatbelt", 500},
{"AA8", "Illegal_Parking", 200},
{"AA9", "Overspeeding", 1200},
{"AA10", "Reckless_Driving", 750},
};
您可以輕松地將數據放入數組中,而不是十個單獨的變量:
struct violation violations[] = {
{"AA1", "Defective_Brakes", 150},
{"AA2", "Disregarding_Traffic_Signs", 150},
{"AA3", "Driving_Under_the_Influence_of_Liquor", 2000},
{"AA4", "Driving_while_using_Mobile_Devices", 200},
{"AA5", "Drinving_without_License", 750},
{"AA6", "Driving_Against_Traffic", 2000},
{"AA7", "Failure_to_use_Seatbelt", 500},
{"AA8", "Illegal_Parking", 200},
{"AA9", "Overspeeding", 1200},
{"AA10", "Reckless_Driving", 750}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.