# C語言結構體

C語言中的結構體是一種使用者定義的資料型別，可以儲存不同型別的資料元素。

## 定義結構體

`struct`關鍵字用於定義結構體。下面我們來看看在C語言中定義結構體的語法。

``````struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
``````

``````struct employee
{   int id;
char name[50];
float salary;
};
``````

## 宣告結構體變數

1. 通過`main()`函式中的`struct`關鍵字
2. 通過在定義結構時宣告變數。

``````struct employee
{   int id;
char name[50];
float salary;
};
``````

``````struct employee e1, e2;
``````

``````struct employee
{   int id;
char name[50];
float salary;
}e1,e2;
``````

## 存取結構成員

• 通過符號`.` (成員或點運算子)
• 通過符號 `->`(結構指標運算子)

``````p1.id
``````

## 結構體範例

``````#include <stdio.h>
#include <string.h>
struct employee
{
int id;
char name[50];
}e1;  //declaring e1 variable for structure

int main()
{
//store first employee information
e1.id = 1010;
strcpy(e1.name, "Max Su");//copying string into char array
//printing first employee information
printf("employee 1 id : %d\n", e1.id);
printf("employee 1 name : %s\n", e1.name);
return 0;
}
``````

``````employee 1 id : 1010
employee 1 name : Max Su
``````

``````#include <stdio.h>
#include <string.h>
struct employee
{
int id;
char name[50];
float salary;
}e1, e2;  //declaring e1 and e2 variables for structure

int main()
{
//store first employee information
e1.id = 1001;
strcpy(e1.name, "Max Su");//copying string into char array
e1.salary = 18000;

//store second employee information
e2.id = 1002;
strcpy(e2.name, "Julian Lee");
e2.salary = 15600;

//printing first employee information
printf("employee 1 id : %d\n", e1.id);
printf("employee 1 name : %s\n", e1.name);
printf("employee 1 salary : %f\n", e1.salary);

//printing second employee information
printf("employee 2 id : %d\n", e2.id);
printf("employee 2 name : %s\n", e2.name);
printf("employee 2 salary : %f\n", e2.salary);

return 0;
}
``````

``````employee 1 id : 1001
employee 1 name : Max Su
employee 1 salary : 18000.000000
employee 2 id : 1002
employee 2 name : Julian Lee
employee 2 salary : 15600.000000
``````