[討論] 用指標排序?

看板C_and_CPP作者 (lkking)時間4年前 (2020/05/09 11:27), 編輯推噓0(005)
留言5則, 1人參與, 4年前最新討論串1/1
如題,小弟最近剛學c++(學到指標陣列這邊),剛剛在用指標排序數字時,有點問題 題目如下: 有多筆測資以EOF為結束 第一行有一個正整數n(1<=n<=1000),代表有幾個數字要排 第二行有n個可以用int儲存的正整數 例如: 6 7 9 0 4 1 8 8 1 9 9 0 0 9 2 8 我的碼: #include <iostream> #include <cstdlib> using namespace std; int *ptr,i,p,index; void fc(int); int main(void) { while(scanf("%d",&i)!=EOF){ ptr=(int*)malloc(i*4); fc(i); free(ptr); } return 0; } void fc(int p){ int j,k,stay; for(index=0;index<p;index++,ptr++){ cin>>*ptr; } ptr-=p; for(j=0;j<p;j++){ for(k=0;k<(p-1);k++){ if(*(ptr+k)>*(ptr+k+1)){ stay=*(ptr+k); *(ptr+k)=*(ptr+k+1); *(ptr+k+1)=stay; } } p--; } p=i; for(index=0;index<p;index++,ptr++){ cout<<*ptr; } } 問題如下: 1. main()的return值是一堆數字 2.讀完第一筆測資就結束了 小弟第一次在c++版發問,排版稍亂還請見諒。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.167.52.127 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1588994830.A.F7F.html

05/09 14:06, 4年前 , 1F
你在輸出看到的是你用 cout 輸出的結果,並不是 main
05/09 14:06, 1F

05/09 14:06, 4年前 , 2F
回傳的值。fc 最後在輸出排序結果後沒有把 ptr 扣回去
05/09 14:06, 2F

05/09 14:06, 4年前 , 3F
,所以在 free 的時候出問題,導致程式沒繼續跑。
05/09 14:06, 3F

05/09 14:06, 4年前 , 4F
你可以先從「想清楚 fc 要做啥、需要哪些參數?」開始
05/09 14:06, 4F

05/09 14:06, 4年前 , 5F
改善這隻程式
05/09 14:06, 5F
文章代碼(AID): #1UjYCEz_ (C_and_CPP)