[問題] 很基礎的純c問題(structure,pointer)

看板C_and_CPP (C/C++)作者 (a29988122)時間16年前 (2010/06/12 20:27), 編輯推噓0(0012)
留言12則, 3人參與, 最新討論串1/1
在作的是考試的考古題,有一份標準解答http://tinyurl.com/2935pl3 以下這份是我自己打的(標準解的寫法看得很不習慣所以用自己的打法,但是有錯) compiler是VC 2008 打出來有幾個地方的用意看不太懂... 而且compile會過,執行會錯,跳access violation,大概是指標寫得不對 以下是code,打紅字的是看不懂的行,不知各位程設眾能否賜教大一生 qq 可能真的有點太新手..不過我想了快1hr,查了很多reference看不懂 囧 如果能不吝指教的話,非常感謝<(_ _)> -- 題目:定義一結構,包含學生姓名 學號 成績三欄位 主程式先要求輸入學生人數,用new配置學生結構該有的大小 把結構傳到另外寫的input function,用另寫的output function來輸出 等input output function呼叫完後,把new配置的空間刪掉 -- // 1.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdlib.h> struct sct{ char name[10]; char sid[10]; int score; }*p; //宣告一個指標p指到sct此結構,對嗎? void input(sct p[], int num); void output(sct p[], int num); //型別搞不清楚,該寫p[]還是*p,解答寫p[]可是不懂為何要寫成陣列,傳的不是指標嗎 int _tmain(int argc, _TCHAR* argv[]) { int num; printf("How many stduents are there?"); scanf("%d,&num"); struct sct *p = new sct[num]; //這行的寫法看不懂,為何這麼寫就可以分配結構sct的大小?這不是compiler自己分配的嗎 input(p,num); output(p,num); delete [] p; //為何不是delete [] struct sct? system("pause"); return 0; } void input (sct p[], int num){ //同之前的prototype型別問題 int i; for(i=0;i<num;i++){ printf("%dth name:",i); scanf("%s",p->name[i]); printf("%sth sid:",i); scanf("%s",p->sid[i]); printf("%dth score:",i); scanf("%d",&p[i].score); //看不懂表示法,且為何要加取址變數 } } void output (sct p[], int num){ int i; for(i=0;i<num;i++) printf("num %d,name %s,sid %s,score %d", i, p->name[i], p->sid[i], p[i].score); //看不懂表示法,為什麼是"p陣列"裡的第i個?前面都還看得懂.. } -- AE拖車冰腳放在ROG群旁邊先讓他們趴掉 再猛打OT吸怪過來放冰箱害死身邊的WLK 隱形後不解咒不補灼燒不喝紅只嗑藍水開始無腦火球硬衝DPS                       ~每個法師都該學的一課~ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.64.66.226

06/12 20:34, , 1F
google "c++ dynamic allocation"
06/12 20:34, 1F

06/12 20:44, , 2F
struct sct *p = new sct[num];相當於宣告有幾個學生
06/12 20:44, 2F

06/12 20:45, , 3F
然後取得那樣大小的記憶體空間
06/12 20:45, 3F

06/12 20:46, , 4F
他宣告後就變成struct sct p[num] 所以後面都用陣列操
06/12 20:46, 4F

06/12 20:47, , 5F
作..應該吧><
06/12 20:47, 5F

06/12 20:49, , 6F
大概看了一下code。 printf("%sth sid:",i); 不對。
06/12 20:49, 6F

06/12 20:50, , 7F
scanf("%d,&num"); 不對。
06/12 20:50, 7F

06/12 20:53, , 8F
另外,name和sid輸入不能超過9個字元,且不能有空白。
06/12 20:53, 8F

06/12 20:53, , 9F
不曉得您輸入得如何?
06/12 20:53, 9F

06/12 22:28, , 10F
p->name[i]這種用法錯誤吧?
06/12 22:28, 10F

06/13 00:48, , 11F
語意上達不到編寫程式者的要求。語法上是單個字元。
06/13 00:48, 11F

06/13 09:47, , 12F
嗯嗯 應該是說語意上可能有問題
06/13 09:47, 12F
文章代碼(AID): #1C4tqyoj (C_and_CPP)
文章代碼(AID): #1C4tqyoj (C_and_CPP)