Last Updated on 2021-04-29 by Clay
結構(Structures)是將多個相關的變數(可能含有多種不同的資料型態的變數)儲存於『一個名稱』底下方便掌握的型態。
基本上,struct
的宣告方法如下:
struct struct-name {
data-type variable_1;
data-type variable_2;
...
} v1, v2, ..., vn;
struct 使用方法
#include <stdio.h> struct point { int x; int y; }; // Main int main() { struct point a = {-1, -1}; struct point b = {2, 3}; return 0; }
這樣的寫法當然是可以的。不過若是將來修改了 struct
的屬性,那麼我們的變數宣告就得跟著一起修改程式碼。
#include <stdio.h> struct point { int x; int y; }; // Main int main() { struct point a = { .x = -1, .y = -1 }; struct point b = { .x = 2, .y = 3 }; return 0; }
甚至我們可以再簡化一點,配合 typedef
來簡化結構對變數的宣告。
#include <stdio.h> typedef struct point point; struct point { int x; int y; }; // Main int main() { point a = { .x = -1, .y = -1 }; point b = { .x = 2, .y = 3 }; return 0; }
而結構也能將結構宣告在內。
#include <stdio.h> // TYPEDEF typedef struct point point; typedef struct rect rect; // STRUCT struct point { int x; int y; }; struct rect { point a; point b; }; // Main int main() { // Init point a = { .x = -1, .y = -1 }; point b = { .x = 2, .y = 3 }; // Rect rect area = { .a = a, .b = b }; return 0; }
結構(Struct)與函式(Function)
若要是撰寫函式(function)並回傳我們自定義的結構,那自然也是可以的。看看以下這段範例程式碼:
#include <stdio.h> // TYPEDEF & STRUCT typedef struct point { int x; int y; } point; typedef struct rect { point a; point b; } rect; rect getRect(point a, point b) { rect area = { .a = a, .b = b }; return area; } // Main int main() { // Init point a = { .x = -1, .y = -1 }; point b = { .x = 2, .y = 3 }; // Rect rect area = getRect(a, b); printf("area.a: (%d, %d)\n", area.a.x, area.a.y); printf("area.b: (%d, %d)\n", area.b.x, area.b.y); return 0; }
Output:
area.a: (-1, -1)
area.b: (2, 3)
References
- https://www.programiz.com/c-programming/c-structures
- https://www.programiz.com/c-programming/c-structure-function
- https://www.tutorialspoint.com/cprogramming/c_structures.htm