參考文檔:https://baijiahao.baidu.com/s?id=1606137789197451791&wfr=spider&for=pc
結構體
一個或多個變量的集合,這些變量的類型可以不同。爲了處理方便將變量組織在一個名字下。
例如:統計某班學生的信息(包括學號、姓名、成績),每個學生需要至少三個變量,如果學生人數較多,那需要的變量就非常多了。這就用到結構體了。
結構體定義
struct Student{
int num;
char name[20];
int score;
};
struct爲關鍵字,student爲結構體的類型名,num,name,score爲結構體的成員。
分號一定要加,分號前面可以加結構體變量,如下
struct Student{
int num;
char name[20];
int score;
}Zhangsan;
上面類似於變量的聲明
定義結構體變量
方式一: 先定義結構體類型,再定義變量
struct Student{
int num;
char name[20];
int score;
};
struct student Zhangsan;
方式二:在定義結構體類型同時,定義變量
struct Student{
int num;
char name[20];
int score;
}Zhangsan, Lisi;
方式三:typedef重定義結構體類型名
typedef struct Student{
int num;
char name[20];
int score;
}students;
Students Zhangsan, Lisi;
方式四:省略結構體類型名
struct {
int num;
char num[20];
int score;
}Zhangsan, Lisi;
不能再增加變量。
結構體變量的初始化
struct Student{
int num;
char name[20];
int score;
};
struct student Zhangsan = {1011, "Zhangsan", 89};
擴展示例
struct Block{ WORD dir[4]; COLORREF color; }g_Blocks[3] = { {0x0F00, 0x4444, 0x0F00, 0x4444, RED}, {0x0660, 0x0660, 0x0660,0x0660, BLUE}, {0x4460, 0x02E0, 0x0622, 0x0740, MAGENTA} };
結構體變量的應用
結構體變量成員的引用:結構體變量名.成員名
Zhangsan.num = 1011;
scanf("%d", &Zhangsan.score);
printf("%d %d\n", Zhangsan.num, Zhangsan.score);
- 當結構體變量的成員也是結構體類型時,引用必須是最底層的成員變量,如下
3. 成員名可與程序中的變量名同名,二者代表不同對象
- 、可以引用結構體變量成員的地址,也可以引用結構體變量的地址,例如:
scanf("%d", &A.num); //輸入A.num的值
printf("%d", &A); //輸出Bob的首地址
目的:主要用作函數參數,傳遞結構體變量的地址。
5、允許具有相同類型的結構變量可以相互賦值,其它情況不允許對結構變量直接賦值。