1.普通結構體
- 結構體:自定義的一種數據類型 關鍵字:struct
struct 結構體名{
類型說明符 成員名;
…..
類型說明符 成員名;
}; - 賦初值:
struct 結構體名 變量名 = {初值}; - 結構體成員變量訪問:
struct teacher{ // 結構體定義
char name[20];
char gender;
int age;
char major[10];
};
struct teacher stu1 = {"balabala", 'f', 28, "iOS"};
stu1.name = "zhangsan"; // 結構體成員變量的訪問及賦值
stu2.age = 32; // 訪問:-----結構體變量名.成員變量名-----
2.匿名結構體
- 結構體的聲明與變量定義組合在一起:
struct {
int number;
int age;
}
stu1 = {1, 23}
stu2 = {2, 34];
typedef:定義類型
oc中:
typedef int Integer; // 之後的int類型數據定義時,可以使用Integer替換
struct student{
int number;
int age;
}
typedef struct student Student; // 將結構體struct student定義爲Student
typedef struct student {
char name[20];
int number;
int age;
float score;
}Student; // 起別名
2.結構體內存佔用:
結構體成員變量,從上至下存儲,從第一個開始
存儲規則:按各種數據類型的倍數存儲,如果被佔用,向下延續
總空間的字節數 = 最大類型變量字節數的最小整數倍
例:
int a;
double b;
char c;
int d;
char e; // 需要分配32字節的空間
解釋:
a: 0–3
b: 8–15 因爲b是double型數據,所以要找8的倍數存儲b
c: 16
d:20–23
e: 24 總共佔用25個字節,double(8)的倍數:24,32 因爲25>24 所以補齊到32各字節0—-31
3.結構體嵌套使用:
typedef struct birthday{
int year;
int month;
int day;
}Birthday;
typedef struct person{
char name[20];
int age;
float high;
float weight;
char gender;
Birthday date; // 結構體嵌套 訪問:結構體變量名.date.year
}Person;
3.結構體數組
- 定義:
typedef struct student{
char name[20];
int age;
char gender;
float score;
}Student;
Student stu[5] = { {...}, {...}, {...}, {...}, {...} };