# 重拾 C 語言::其他部分 ## C Preprocessor [Link](https://blog.xuite.net/jesonchung/scienceview/93554778-C%2FC%2B%2B+%E7%9A%84%E9%A0%90%E8%99%95%E7%90%86%E5%AE%9A%E7%BE%A9+%3A+%23+%2C++%23%40+%2C+%23%23) ## C的內存結構 主要分為四大類: - Stack 主要用來儲存 Function calls 和 Local variables 。 Stack 的最底層為 `main()` ,調用函數時執行 `push()` ,函數 `return` 時執行 `pop()` 。 - Heap 當我們使用 `malloc`, `calloc` 動態分配記憶體空間時,這些記憶體位置都屬於 Heap 內存。 > 如果使用 `malloc()` 時返回了 `null` ,代表這一塊空間快要用盡了。 - Static 使用 `static` 關鍵字聲明的變數會被放到該空間。 > 補充: [ static 的用途](https://medium.com/@alan81920/c-c-%E4%B8%AD%E7%9A%84-static-extern-%E7%9A%84%E8%AE%8A%E6%95%B8-9b42d000688f) - Code 存放二進制指令和其他必要文件 ## #ifdef [Link](https://www.1ju.org/cprogramming/c-preprocessor-ifdef) ## 多檔開發 使用`標頭檔`定義方法: ```c= /* File add.h */ #ifdef ADD_H #define ADD_H int add(int, int); #endif ``` `同名.c` 實做方法: ```c= /* File add.c */ #include "add.h" int add(int a, int b) { return a + b; } ``` 引用標頭檔直接使用函式: ```c= /* File triple.c */ #include "add.h"; int triple(int x){ return add(x, add(x, x)); } ``` ## Struct ```c= typedef struct person_t person_t; struct person_t { char *name; unsigned age; }; int main(void){ person_t p ={ "Ian", 37 }; } ``` ### 預防寫死 上面範例中的初始化結構方式寫死該結構的屬性的位置,若屬性有更動需一併更動相關程式碼,在軟工觀點上不佳。可以改用以下的方法來初始化結構: ```c= #include <assert.h> struct person_t p = { .name = "Michael", .age = 37 }; assert(pt.x == 3);// 存取結構內屬性 return 0; ``` ### 補充 ```c typedef struct person_t person_t; ``` 第一個 `person_t` 為結構名稱,第二個 `person_t` 為自定義型別名稱: ```c person_t p ={ "Ian", 37 }; ``` ### 節省記憶體 [記憶體對齊](https://chenlen.com/%E8%A8%AD%E8%A8%88%E8%B3%87%E6%96%99%E7%B5%90%E6%A7%8B%E7%AF%80%E7%9C%81%E8%A8%98%E6%86%B6%E9%AB%94%E7%9A%84%E5%B0%8F%E6%92%87%E6%AD%A5/)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up