75_iOS乾貨41_結構體總結
阿新 • • 發佈:2018-11-15
一,結構體的定義
- 定義的同時,初始化
-
struct Dog { char *name; int age; double height; }; struct Dog sd = {"wc", 13, 5.0};
-
- 先定義,再逐個初始化
-
struct Dog { char *name; int age; double height; }; struct Dog sd1; sd1.name = "ww"; sd1.age = 5; sd1.height = 10.9;
-
- 先定義,再一次性初始化
-
struct Dog { char *name; int age; double height; }; struct Dog sd2; // 特別注意: 結構體和陣列有一點區別, 陣列不能先定義再進行一次性的初始化, 而結構體可以 // 只不過需要明確的告訴系統{}中是一個結構體 sd2 = (struct Dog){"xq", 8, 8.8};
-
- 指定將資料賦值給指定的屬性
-
struct Dog { char *name; int age; double height; }; // 指定將資料賦值給指定的屬性 struct Dog sd3 = {.height = 1.77, .name = "ww", .age = 33};
-
- 定義結構體時,定義結構體變數
-
struct Dog { char *name; int age; double height; } sd4; sd4.age = 30;
-
- 定義結構體型別的同時定義結構體變數, 並且省略結構體名稱
-
struct { char *name; int age; double height; }sd5; sd5.age = 10; // 弊端: 由於結構體型別沒有名稱, 所以以後就不能使用該結構體型別 // 優點: 如果結構體型別只需要使用一次, 那麼可以使用該方式
-
- typeDefine定義結構體
-
typedef struct { int year; int month; int day; } MyDate2; // 結構體型別變數為 d2,並賦值 MyDate2 d2 = {2016, 5, 24};
-
- 蘋果官方結構體
-
//CGSize結構體定義 struct CGSize { CGFloat width; CGFloat height; }; typedef struct CG_BOXABLE CGSize CGSize; //CGSize設定方法結構體定義 CG_INLINE CGSize CGSizeMake(CGFloat width, CGFloat height) { CGSize size; size.width = width; size.height = height; return size; } //行內函數和巨集 CG_INLINE:CG_INLINE is a #define for static inline. This causes the compiler to create the code for the function inline, rather that creating a function call on the stack. See here and here for more information
-
- 仿照蘋果官方的自定義結構體
-
//自定義結構體 struct ClickSize { CGFloat top; CGFloat left; CGFloat bottom; CGFloat right; }; typedef struct ClickSize ClickSize; /* 也可以用以下方法代替上述 typedef struct ClickSize { CGFloat top; CGFloat left; CGFloat bottom; CGFloat right; } ClickSize; */ //自定義結構體設定方法 CG_INLINE ClickSize ClickSizeMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right) { ClickSize clickSize; clickSize.top = top; clickSize.left = left; clickSize.bottom = bottom; clickSize.right = right; return clickSize; };
-
二,儲存空間
會獲取結構體型別中佔用記憶體最大的屬性的大小, 然後取該大小的倍數
三,訪問結構體變數的方法
- 結構體變數名稱.屬性;
-
struct Person { int age; char *name; double height; }; struct Person sp = {30, "ln", 1.75}; sp.name = "lnj";
-
- (&結構體變數名稱)->屬性;
-
struct Person { int age; char *name; double height; }; struct Person sp = {30, "ln", 1.75}; (&sp)->age = 20;
-
- (*結構體指標變數名稱).屬性;
-
struct Person { int age; char *name; double height; }; struct Person sp = {30, "ln", 1.75}; struct Person *sip; sip = &sp; (*sip).age = 88;
-
- 結構體指標變數名稱->屬性;
-
struct Person { int age; char *name; double height; }; struct Person sp = {30, "ln", 1.75}; struct Person *sip; sip = &sp; (*sip)->age = 88;
-