介紹結構 — structures

Sharon Peng
5 min readAug 29, 2019

--

終於結束複雜的指標了,換一個新的標題,但是這個單元也很注重指標的運用,希望各位不要忘記啊~

什麼是結構(structures)?

結構是使用者自已可以定義的資料型態,裡面可以把不同的資料型態聚集在一起。例如:我們想要做學生的個人資料(名子、學號、身高、體重…)時,struct會是非常實用的方法。

1. struct的宣告:

先打關鍵字struct,裡面要有成員,最後在中括弧後面要加上分號,分號很容易忘記,一定要記得!

struct 名稱 
{
char name[40];
char id_num[20];
float height;
};

*struct裡面的成員可以包含任何型態,array, pointer, strings…..,甚至其他的struct也都可以被放入裡面。

再來,當我們宣告完struct內的資料型態後,我們還要在外面在宣告一個他自己的名稱(可以想做是變數名稱,struct是他的資料型態)。

struct student
{
char name[40];
char id_num;
float height;
};
struct student s1; // 這邊的s1代表,學生s1的個人資料
struct student s2; // 這邊的s1代表,學生s1的個人資料

2. 那我們要怎麼把學生資料放到 s1,s2 變數呢?

第一種初始化的方法:直接初始化

struct student
{
char name[40];
int id_num;
float height;
};
struct student s1 = {"Kevin", "1234567", 181.6};
struct student s2 = {"Valerie", "987654", 161.7};

第二種初始化的方法:使用資料型態轉換

struct student
{
char name[40];
int id_num;
float height;
};
struct student s1;
struct student s2;
// 使用型態轉換的方式
s1 = (struct student) {"Kevin", "1234567", 181.6};
s2 = (struct student) {"Valerie", "987654", 161.7};

第三種初始化的方法:進入struct中的成員來初始化

struct student
{
char name[40];
char id_num[20];
float height;
};
struct student s1 = {.name = "Kevin", .id_num = "1234567", .height = 181.6};
struct student s2 = {.name = "Valerie", .id_num = "987654", .height = 161.7};

3. 進入結構成員:

當我們想要進入結構成員中修改資料,我們要加 .(dot operator)在變數名稱跟成員名稱之間。

s1.name = "Jack";

也可以直接把相同型態的struct直接賦予給另一個相同型態的struct。

struct student
{
char name[40];
char id_num[20];
float height;
};
struct student s1 = {"Kevin", "1234567", 181.6};
struct student s2;
s2 = s1; // 把s1的直更改得和s2相同

完整範例:

#include<stdio.h>
#include<string.h> // using strcpy
struct student
{
char name[40];
char id_num[20];
float heigth;
};
int main()
{
struct student s1 = {"Kevin", "1234567", 181.6};
struct student s2;

s2 = s1;
strcpy(s2.name, "Jack");
s2.heigth = 178.3;


printf("%s %s %.2f\n", s1.name, s1.id_num, s1.heigth);
printf("%s %s %.2f\n", s2.name, s2.id_num, s2.heigth);
return 0;
}

4. typedef的使用:

關鍵字typedef 可以讓struct的名稱更方便我們使用,不用每一次要宣告struct時,要打一大堆文字,現在只要輸入一個我們幫他取的綽號即可,這也更容易我們閱讀。

typedef struct 
{
char name[40];
char id_num[20];
float heigth;
} student;

student s1; //不用再宣告struct student s1
student s2;

今天這章就到這啦~謝謝各位讀者耐著性子看完它。

--

--

Sharon Peng
Sharon Peng

No responses yet