[問題] 以函式SWAP() 交換陣列

看板C_and_CPP (C/C++)作者 (于)時間13年前 (2013/03/28 22:13), 編輯推噓1(101)
留言2則, 2人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Visual C++ 2010 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 傳址? 傳值? 傻傻搞不清楚 餵入的資料(Input): int 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) #include "stdafx.h" #include <stdlib.h> #include <stdio.h> void swap(int &,int &) ; #1 int _tmain(int argc, _TCHAR* argv[]) { int a[5] , i , j , n , temp ; printf("\n ===== 泡沫排序法 =====") ; printf("\n 輸入五個數字 , 中間以空白隔開 : ") ; printf("\n 排序前 : ") ; for(i=0 ; i<=4 ; i++) { scanf("%d", &n) ; a[i] = n ; } for(i=3 ; i>=0 ; i--) { for(j=0 ; j<=i ; j++) { if(a[j]>a[j+1]) { swap(a[j],a[j+1]) ; #2 } } } printf("\n 排序後 :") ; for(i=0 ; i<=4 ; i++) { printf(" %d",a[i]) ; } printf("\n\n") ; system("pause") ; return 0; } void swap(int &x, int &y) #3 { int temp ; temp = x ; x = y ; y = temp ; } 補充說明(Supplement): 其實就只是氣泡排序 但是就不想照本來的方法做 if(a[j]>a[j+1]) { temp = a[j] ; a[j] = a[j+1] ; a[j+1] = temp ; } 就想把他寫成函式 一開始傳陣列位址 函式用指標接 ex: if(a[j] > a[j+1]) { swap(&a[j],&a[j+1]) ; } 但函式內容怎麼寫都寫不對 就上網找 找出這個解法 可是完全看不懂原理是怎樣 黃色標色是我的疑問 #2 處的 swap(a[j],a[j+1]) 是否是隨著 #1#3 處的 void swap(int &,int &) ; void swap(int &x,int &y) 宣告而會傳遞不同的資料 如果我是宣告 void swap(int,int) & void swap(int x,int y) 就會進行傳值 而 void swap(int &,int &) ; void swap(int &x,int &y) 情況下是傳址 ? 而這種方式的傳遞 真的看不太懂 請大大解惑 感恩 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 219.70.200.246

03/28 22:18, , 1F
這個叫做 call by reference 去查這個詞吧
03/28 22:18, 1F

03/28 22:35, , 2F
太感謝 LPH大 懂了 感恩
03/28 22:35, 2F
文章代碼(AID): #1HL4_wqY (C_and_CPP)
文章代碼(AID): #1HL4_wqY (C_and_CPP)