[問題] 如何在struct指標中使用enum?
開發平台(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
11/20 01:00, 1F
→
11/20 01:00, , 2F
11/20 01:00, 2F
→
11/20 01:00, , 3F
11/20 01:00, 3F
→
11/20 01:01, , 4F
11/20 01:01, 4F
推
11/20 01:02, , 5F
11/20 01:02, 5F
→
11/20 07:10, , 6F
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
11/22 00:01, 9F
推
11/24 02:32, , 10F
11/24 02:32, 10F
→
11/24 11:55, , 11F
11/24 11:55, 11F