[問題] 如何在struct指標中使用enum?

看板C_and_CPP作者 (Monitor)時間11年前 (2014/11/20 00:48), 11年前編輯推噓6(605)
留言11則, 7人參與, 最新討論串1/1
開發平台(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

11/20 01:00, , 1F
mystruct 是指標, 剛生出來它並不指到一個合法位置
11/20 01:00, 1F

11/20 01:00, , 2F
你必須要 malloc 一塊給它
11/20 01:00, 2F

11/20 01:00, , 3F
17 沒事是運氣好而已
11/20 01:00, 3F

11/20 01:01, , 4F
這跟 enum 沒有關係
11/20 01:01, 4F

11/20 01:02, , 5F
你的mystruct是指標,要先malloc.
11/20 01:02, 5F

11/20 07:10, , 6F
搞錯重點了,你的mystruct沒有malloc
11/20 07:10, 6F
謝謝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

11/20 23:11, , 7F
恭喜你跨過重要的一關
11/20 23:11, 7F

11/21 03:01, , 8F
11/21 03:01, 8F
※ 編輯: OPIV (114.37.128.191), 11/21/2014 23:55:25

11/22 00:01, , 9F
恭喜你.. 得到 memory leak 一玫 ...
11/22 00:01, 9F

11/24 02:32, , 10F
樓上XDDDDD
11/24 02:32, 10F

11/24 11:55, , 11F
malloc後可以free;man malloc有寫,在同一行很難不讀到
11/24 11:55, 11F
文章代碼(AID): #1KRCdU5i (C_and_CPP)