[問題] struct陣列在main和函數裡的size不同

看板C_and_CPP作者 (香蕉)時間15年前 (2010/07/11 16:31), 編輯推噓2(205)
留言7則, 2人參與, 最新討論串1/1
( *[1m *[m 為色碼,可以按 Ctrl+V 預覽會顯示的顏色 ) ( 未必需要依照此格式,文章條理清楚即可 ) 遇到的問題: (題意請描述清楚) 用strutc宣告一個陣列 有名字和分數 用一個函數找出這個陣列中分數最高的 return值為struct型態 希望得到的正確結果: 9999 程式跑出來的錯誤結果: 99 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) wxDEV-C++ 有問題的code: (請善用置底文標色功能) struct data { char name[10]; int math; }; struct data best(struct data student[]); int main() { int MAX=5; struct data student[5]={{"A",99},{"B",59},{"c",11},{"D",9999},{"E",78}}; printf("In main, sizeof(student) = %d\n", sizeof(student)); printf("Max score = %d\n",best(student).math); system("pause"); return 0; } struct data best(struct data student[]) { int i=0; int j=0; int max=(student+0)->math; printf("In best, sizeof(student) = %d\n", sizeof(student)); printf("In best, sizeof(student[0]) = %d\n", sizeof(student[0])); for(i=1; i<(sizeof(student)/sizeof(student[0])); i++) { printf("i = %d\n",i); if((student+i)->math>max) { max=(student+i)->math; j=i; } } return *(student+j); } 跑出結果: In main, sizeof(student) = 80 In best, sizeof(student) = 4 // 這行的結果我不知道為什麼會這樣... In best, sizeof(student[0]) = 16 Max score = 99 所以在best函數裡 for 迴圈沒有執行到 Max的output就是student[0]的math值 -- ˋ〃ˊ╔═╦══╦════╗ @︵@宅度0 ∵)3∵ ◢█◣  ╠══╬════╣ ▊star..█ █  魅力10000000 fuck ██ ◥█◤ ╚═╩══╩════╝ ███ by lordwill -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.243.53.253

07/11 16:40, , 1F
best裡的sizeof(student)沒有辦法像main裡一樣正確的算
07/11 16:40, 1F

07/11 16:41, , 2F
出你想要的東西, sizeof用在array上要在array被定義的地
07/11 16:41, 2F

07/11 16:41, , 3F
方才會算出你想要的結果; 結論, 直接把array大小從main
07/11 16:41, 3F

07/11 16:41, , 4F
傳進best裡去算吧....
07/11 16:41, 4F

07/11 16:44, , 5F
另外, 用sizeof在本板搜尋也可以找出討論過的類似問題,
07/11 16:44, 5F

07/11 16:44, , 6F
請見 #1BDSy4aw#1BDuwKox 等文章....
07/11 16:44, 6F

07/11 16:46, , 7F
有點懂了 謝謝~
07/11 16:46, 7F
文章代碼(AID): #1CEO5-tQ (C_and_CPP)