史萊姆論壇

史萊姆論壇 (http://forum.slime.com.tw/)
-   一般電腦疑難討論區 (http://forum.slime.com.tw/f17.html)
-   -   C語言的問題:如何指標改參考呼叫 (http://forum.slime.com.tw/thread113911.html)

8533667 2004-06-20 08:09 PM

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:

Leech 2004-06-20 10:26 PM

請試試...

void swap(int&, int& );
int main(void)
{
...
swap(a, b);
...
}

void swap(int &x, int &y)
{
int temp = x;
x = y;
y = temp;
return;
}

8533667 2004-06-20 11:44 PM

是改成這樣嗎?
 
/* 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;
}

Leech 2004-06-21 12:30 PM

嗯...是的...
不過我是憑印象寫的, 沒有實際編譯過:p

mini 2004-06-21 01:25 PM

就如最後 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) 的引數呼叫

8533667 2004-06-21 05:59 PM

但...我改好後~執行編譯有出現錯誤耶:drtyt76h6

Leech 2004-06-21 10:08 PM

引用:

原文由 8533667 所發表
但...我改好後~執行編譯有出現錯誤耶:drtyt76h6

錯誤的行數及訊息是?

mini 2004-06-21 11:35 PM

我想應該錯在
void swap(int &x, int &y) /* 將兩數互換 */
{
int temp=x;
x=y;
y=temp;
return;
}

首先 return;
不需要
再來
int temp=x;
改成
int *temp=&x;

8533667 2004-06-21 11:37 PM

抱歉!~已經沒問題了~謝謝!只是程式執行完後就不見了~
如何加入暫停的程式碼啊?:dcft689kj

mini 2004-06-22 08:24 AM

#include <iostream>
#include <conio.h>

void main()
{

getche();
}

jerryhung 2004-06-22 01:21 PM

哈哈,我剛好最近才看到另一個更妙的方法來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.

『服務條款』

* 有問題不知道該怎麼解決嗎?請聯絡本站的系統管理員 *


SEO by vBSEO 3.6.1