Re: [問題] C++以函數傳送陣列,而以指標方式接收

看板Programming作者 (windf4)時間17年前 (2007/04/11 20:14), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串3/8 (看更多)
※ 引述《quota (怎樣轉移檔案?)》之銘言: : 我想以函數傳送陣列,而以指標方式接收 : 不過結果卻讓人失望,附上我的原始碼, : 請各位幫我看看是哪裡出了問題,謝謝! : #include <iostream> : using namespace std; : void array_dump(int *a, int size ) : { : int *ptr; : for ( ptr = a; ptr < (a+size) ; ptr++ ) : cout << *ptr ; : cout << endl; : } 改用 cout << " " << *ptr; 的寫法,輸出會好看得多。 : void bubble_sort(int *a, int size) : { : int i,temp; : int *ptr; : for( i = 0 ; i < size ; i++ ) : for( ptr = a; ptr < (a+size) ; ptr++ ) : { : if( *ptr < *(ptr+1) ) : { : temp=*(ptr+1); : *(ptr+1)=*ptr; : *ptr=temp; : } : array_dump(a,size); : } : } 內圈的 for 存取了超出陣列範圍的元素,合理範圍是從 a+0 ~ a+size-1 因為 if 會取到 ptr+1 所以只要做 a ~ a+size-2 的部份[或 a+1 ~ a+size-1 ] 另外 bubble sort 不需要做那麼多次,內迴圈的次數會逐次少1 main 的部份沒什麼問題恕刪。 -- 另外寫程式請記得縮排,適當的排版對寫作和閱讀除錯都有幫助。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 125.231.74.249

04/15 01:50, , 1F
謝謝 因為我沒有縮排 所以少了一個{}而不知
04/15 01:50, 1F
文章代碼(AID): #167D4lS1 (Programming)
討論串 (同標題文章)
以下文章回應了本文
完整討論串 (本文為第 3 之 8 篇):
文章代碼(AID): #167D4lS1 (Programming)