看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) LINUX 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) GCC 問題(Question): 宣告一個struct typedef struct { uint8_t var_a; uint8_t var_b; } test_entry_t; 宣告一個指標 test_entry_t *p_entry 宣告一個function function testF(test_entry_t *p_entry){ uint8_t var1 = 0x01 uint8_t var2 = 0x02 p_entry->var_a = var1 p_entry->var_b = var2 } 我嘗試用以下方是來call此function int main(){ test_entry_t *p_entry testF(&p_entry); printf("0x%02X\n", p_entry->var_a); printf("0x%02X\n", p_entry->var_b); 預計輸出結果 0x01 0x02 但是我印出來卻是空的! 想請問各位大大我這段code哪裡寫錯了! 感謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.164.192.107 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1480677124.A.B8D.html ※ 編輯: blueguan (1.164.192.107), 12/02/2016 19:13:00 ※ 編輯: blueguan (1.164.192.107), 12/02/2016 19:13:38
LPH66: 你想要讓 testF 填入 p_entry 指向的東西, 那在傳進 testF 12/02 19:13
LPH66: 時就必須要給一個實際上指向那個 struct 的指標 12/02 19:13
LPH66: 你這樣寫變成傳入一個指向指標的指標, 所以就會有問題 12/02 19:14
LPH66: 正確的做法是 test_entry_t entry; testF(&entry); 12/02 19:14
LPH66: 或者如果你的 struct 是 malloc 來的話: 12/02 19:14
LPH66: test_entry_t *p_entry = (test_entry_t)malloc(...); 12/02 19:15
LPH66: testF(p_entry); 這樣子 12/02 19:15
LPH66: 啊, 上上行少一個 *, 總之意思應該到了 12/02 19:16
blueguan: test_entry_t **p_entry = (test_entry_t)malloc(...); 12/02 19:17
blueguan: 這樣嗎? 12/02 19:17
LPH66: 是轉型少了 *... 12/02 19:18
blueguan: est_entry_t *p_entry = (test_entry_t *)malloc(...); 12/02 19:25
blueguan: 這樣嗎? 12/02 19:26
blueguan: 我改完好像~還是沒有把值塞進去 12/02 19:38
pttworld: 預期輸出的正確結果: 12/02 19:40
※ 編輯: blueguan (1.164.192.107), 12/02/2016 19:46:48
blueguan: 我加入預期輸出結果了... 12/02 19:47
james732: http://ideone.com/OJNIuQ 這樣 12/02 19:54
blueguan: 感謝各位大大~~已經可以了!!!! 各位太威了.. 12/02 20:07
blueguan: 所以我必須要宣告給空間才可以 12/02 20:07