C 語言沒有字串型別,字串本質是「以空字元結尾的字元陣列」,而函式傳遞字串時實際傳遞的是「首字元位址」(即 char*)。
NODE* buildList(char* fileID) {
FILE* fpData = fopen(fileID, "r"); // fileID 是 char*
// ...
}
fileID 的型別是 char*,儲存的是字串首字元的記憶體位址。buildList("data.txt") 或 char path[] = "data.txt"; buildList(path);。"data.txt" 是字串常值,編譯器在唯讀區配置記憶體並回傳其首址。fopen 原型:FILE *fopen(const char *pathname, const char *mode);,參數 pathname 正是 const char*,直接接收首址。*fileID?| 運算式 | 型別 | 值(以 "data.txt" 為例) |
|---|---|---|
fileID | char* | 字串首址(如 0x7ffe...) → 正確傳給 fopen |
*fileID | char | 'd'(首字元) → 傳給 fopen 會當成位址 0x64,導致崩潰 |
fileID[0] | char | 'd' 同上 |
記憶體位址: 0x1000 0x1001 0x1002 0x1003 0x1004 0x1005 0x1006 0x1007 0x1008
儲存內容: 'd' 'a' 't' 'a' '.' 't' 'x' 't' '\0'
↑
fileID (char*) 指向此處
char* 是「字串物件」。\0 判斷結尾。const → void buildList(const char* fileID),防止誤修改字串常值導致未定義行為。char path[PATH_MAX] 陣列配合 snprintf,再傳 path(隱式轉 char*)。fopen(fileID, "r") 能直接使用 char* fileID,是因為 C 語言字串慣例:指標即字串。理解「指標指向首字元、以空字元結尾」這一核心,即可靈活處理檔案路徑、命令列參數、網路封包等所有字串場景。