看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux, GCC 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 在struct中使用enum已經試過沒問題了 可是如果在struct指標裡用enum,在執行的時候就會core dumped(是記憶體區段錯誤) 程式碼: #include <stdio.h> typedef enum { MON, TUE, WED, THU, FRI, SAT, SUN } day; typedef struct { int date; day dayofweek; } *mystruct; int main(int argc, char *argv[]) { mystruct ms; ms->date = 17; printf("%d\n", ms-date); //到這行都OK ms->dayofweek = MON; //這裡出現問題 printf("%d\n", ms->dayofweek); return 0; } 餵入的資料(Input): 預期的正確結果(Expected Output): 17 0 錯誤結果(Wrong Output): 17 core dumped (記憶體區段錯誤) 補充說明(Supplement): 如果我用 typedef struct { int date; day dayofweek; } mystruct; mystruct ms; ms.dayofweek = MON; printf("%d\n", ms.dayofweek); 是可以正常工作的 只是換成指標就會錯誤...... -- Sent from my Android -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.37.128.59 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1416415710.A.16C.html ※ 編輯: OPIV (114.37.128.59), 11/20/2014 01:00:14
LPH66: mystruct 是指標, 剛生出來它並不指到一個合法位置11/20 01:00
LPH66: 你必須要 malloc 一塊給它11/20 01:00
LPH66: 17 沒事是運氣好而已11/20 01:00
LPH66: 這跟 enum 沒有關係11/20 01:01
karose: 你的mystruct是指標,要先malloc.11/20 01:02
Caesar08: 搞錯重點了,你的mystruct沒有malloc11/20 07:10
謝謝LPH66大大的解說! 以下程式碼工作正常! #include <stdio.h> typedef enum { MON, TUE, WED, THU, FRI, SAT, SUN } day; typedef struct { int date; day dayofweek; } mystruct; int main(int argc, char *argv[]) { mystruct *ms = (mystruct *)malloc(sizeof(mystruct)); ms->date = 17; printf("%d\n", ms->date); ms->dayofweek = MON; printf("%d\n", ms->dayofweek); return 0; } ※ 編輯: OPIV (114.37.128.191), 11/20/2014 19:35:39
anakin2: 恭喜你跨過重要的一關11/20 23:11
jammy50605: 推11/21 03:01
※ 編輯: OPIV (114.37.128.191), 11/21/2014 23:55:25
EdisonX: 恭喜你.. 得到 memory leak 一玫 ... 11/22 00:01
jammy50605: 樓上XDDDDD 11/24 02:32
dirkc: malloc後可以free;man malloc有寫,在同一行很難不讀到 11/24 11:55