![]() |
C語言的問題:如何指標改參考呼叫
/* prog 10-12,將a與b值互換(正確範例) */
#include <stdio.h> void swap(int *,int *); int main(void) { int a=3,b=5; printf("Before swap..."); printf("a=%d,b=%d\n",a,b); printf("After swap..."); swap(&a,&b); printf("a=%d,b=%d\n",a,b); return 0; } void swap(int *x,int *y) /* 將兩數互換 */ { int temp=*x; *x=*y; *y=temp; return; } 麻煩那位大大會的!幫我改一下~謝謝:ddrf567h: |
請試試...
void swap(int&, int& ); int main(void) { ... swap(a, b); ... } void swap(int &x, int &y) { int temp = x; x = y; y = temp; return; } |
是改成這樣嗎?
/* prog 10-12,將a與b值互換(正確範例) */
#include <stdio.h> void swap(int &, int & ); int main(void) { int a=3,b=5; printf("Before swap..."); printf("a=%d,b=%d\n",a,b); printf("After swap..."); swap(a,b); printf("a=%d,b=%d\n",a,b); return 0; } void swap(int &x, int &y) /* 將兩數互換 */ { int temp=x; x=y; y=temp; return; } |
嗯...是的...
不過我是憑印象寫的, 沒有實際編譯過:p |
就如最後 8533667 所改的沒錯
這裡做一簡單解釋教學: 參考型態的引數 - call by reference: 函數呼叫 swap(i, j) 時, 引數的 傳遞 如同int &x=i; int &y=j;。 void swap(int &x, int &y) {} main() { int i,j; ... swap(i,j); ... } 解釋: i、x及j、y 是不同名但同體(x是i的別名);以 地址運算子 & 來 達到 call by reference 的功能 而第一樓 8533667 發表的是 位址呼叫(Call by address) 的引數呼叫 |
但...我改好後~執行編譯有出現錯誤耶:drtyt76h6
|
引用:
|
我想應該錯在
void swap(int &x, int &y) /* 將兩數互換 */ { int temp=x; x=y; y=temp; return; } 首先 return; 不需要 再來 int temp=x; 改成 int *temp=&x; |
抱歉!~已經沒問題了~謝謝!只是程式執行完後就不見了~
如何加入暫停的程式碼啊?:dcft689kj |
#include <iostream>
#include <conio.h> void main() { getche(); } |
哈哈,我剛好最近才看到另一個更妙的方法來SWAP兩個變數哦(而且不用使用第三個暫存變數)
要使用C/C++的Bitwise operator XOR let's say x = A, y = B x = x ^ y; y = x ^ y; x = x ^ y; http://www.cs.umd.edu/class/spring20...BitOp/xor.html http://www.if.uidaho.edu/~bgray/clas.../doc/swap.html 要暫停,可加入下面這行(在Windows下) system("PAUSE"); |
所有時間均為台北時間。現在的時間是 02:01 PM。 |
Powered by vBulletin® 版本 3.6.8
版權所有 ©2000 - 2025, Jelsoft Enterprises Ltd.
『服務條款』
* 有問題不知道該怎麼解決嗎?請聯絡本站的系統管理員 *