❶ 什麼是結構體變數
結構體變數簡稱為結構變數,它由結構類型定義,有三種定義方法。下面以定義結構類型 book 和結構變數mybook 、 storybook 為例說明之。
1. 先定義結構類型,再定義結構變數。
struct book /* 定義結構體類型 */
{
char bookname[20];
float price;
char publisher[20];
char author[10];
} ;
struct book mybook, storybook;
用這種方法定義結構變數,是最常用的方法,但須注意不能省略關鍵字「 struct 」。還可以在定義結構變數的同時給它的成員賦初值。如:
struct book /* 定義結構體類型 */
{
char bookname[20];
float price;
char publisher[20];
char author[10];
} ;
struct book mybook = { 「maths」, 24.7, 「 電子社 」, 「zhao」 }, storybook;
則, mybook 變數的 price = 24.7 。
2. 定義結構類型的同時定義結構變數。
struct book /* 定義結構體類型 */
{
char bookname[20];
float price;
char publisher[20];
char author[10];
} struct book mybook, storybook;
3. 不定義結構類型,直接定義結構變數。
struct /* 不定義結構類型名 */
{
char bookname[20];
float price;
char publisher[20];
char author[10];
} struct book mybook, storybook;
需要說明的是,當某結構類型的成員又是另外一個結構類型時,稱嵌套定義,其定義方法如下:
struct brith_date
{
int month ;
int day ;
int year ;
} ;
struct
{
char name[10] ;
char address[30];
char tel[12];
int age;
struct data birthday;
char sex[3];
} student_01 , employee ;
此例直接定義了 student_01 和 employee 兩個變數,但是沒有定義此結構體的名字,因此不能再定義與student_01 和 employee 同類的其它結構變數了!如下行定義是錯誤的:
truct boy, girl;