[問題] 結構內字串的初始化

看板C_and_CPP作者 (no anonymous)時間12年前 (2012/02/04 13:31), 編輯推噓2(2011)
留言13則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question):想請問以下的code: 餵入的資料(Input): 預期的正確結果(Expected Output):原本預期的結果是結構內所有字串都能 被初始化 錯誤結果(Wrong Output):但是卻出現syntax error before '{'token以及 syntax error before '}'token這些錯誤 程式碼(Code):(請善用置底文網頁, 記得排版) struct STUDENT { int id; char name[80]; int take_num; int takes[6]; }; void init(struct STUDENT students[]) { int i,j; for(i=1;i<256;i++) { students[i].id=-1; students[i].name[80]={0}; } } 補充說明(Supplement):請問這應該如何修改呢?? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.251.186.10

02/04 13:48, , 1F
memset(students[i].name, 0, 80); 如何?
02/04 13:48, 1F

02/04 14:13, , 2F
compiler?
02/04 14:13, 2F

02/04 14:20, , 3F
我compiler沒錯啊
02/04 14:20, 3F

02/04 14:20, , 4F
結果正常
02/04 14:20, 4F

02/04 14:25, , 5F
初始化是在定義的時候就要初始化, 不能用在之後
02/04 14:25, 5F

02/04 14:26, , 6F
students[i].name[80]會變成未定義行為
02/04 14:26, 6F

02/04 14:34, , 7F
如果要給值的話要每個都給,多一個80次的loop
02/04 14:34, 7F

02/04 14:34, , 8F
不知道為什麼我compiler可以xdd
02/04 14:34, 8F

02/04 14:47, , 9F
未定義的行為?where?
02/04 14:47, 9F

02/04 14:50, , 10F
name[80]超過宣告範圍呀
02/04 14:50, 10F

02/04 14:52, , 11F
其實POD struct可以直接初始化, 不用透過func另外賦值
02/04 14:52, 11F

02/04 15:36, , 12F
我覺得主要重點是語法問題...語法正確再來看未定義行為..
02/04 15:36, 12F

02/04 15:39, , 13F
連complier都過不了 又如何產生未定義行為...
02/04 15:39, 13F
文章代碼(AID): #1FBCARjx (C_and_CPP)