C語言——經典的兩個數互換的程式——更好的理解指標!!!
阿新 • • 發佈:2018-12-30
# include<stdio.h>
int main(void)
{
void huhuan(int ,int);
void huhuan_1(int *,int *);
void huhuan_2(int *,int *);
int a=3;
int b=5;
//huhuan(a,b);
//huhuan_1(&a,&b);
//huhuan_2(&a,&b);
printf("a=%d,b=%d\n",a,b);
return 0;
}
void huhuan(int a,int b)
{
int t;
t=a;
a=b;
b=t;
return;
}
void huhuan_1(int *p,int *q)
{
int * t;
t=p;
p=q;
q=t;
return;
}
void huhuan_2(int * p,int * q)
{
int t;
t=*p;
*p=*q;
*q=t;
return;
}
【1】執行huhuan(a,b);時,不能互換a和b的值,是因為執行互換函式時,只是互換了形參的值,函式執行結束時,對實參沒做任何改變。
【2】執行huhuan_1(&a,&b);時,不能互換a和b的值,是因為對於指標變數來說,改變地址的值並不改變指標所指向的內容的值。
【3】執行huhuan_2(&a,&b);時,能互換a和b的值,是因為將a,b的地址分別傳遞給了p和q,執行互換函式時,將a和b的原地址對應的內容互換了。
注:指標就是地址;指標變數就是存放地址的變數;改變地址的值並不改變該地址對應的內容的值。當然,互換兩個數的程式有一種簡單的方法,而這裡主要是為了更好的理解指標,故如此!