標(biāo)題: 指針互換的兩種形式(換值or換地址) [打印本頁(yè)]

作者: xiaojuan    時(shí)間: 2014-9-17 14:44
標(biāo)題: 指針互換的兩種形式(換值or換地址)
1......換值不換地址
    函數(shù)形式,此時(shí)函數(shù)可以

#include<stdio.h>
void swap (int * p, int *q)  //下面出現(xiàn)的是地址,所以此時(shí)刻應(yīng)該出現(xiàn)的是指針
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}
int main (void)
{
int a, b;
int * p, * q;
scanf ("%d %d",&a,&b);
p = &a;
q = &b;

if (a
  swap(p,q);  //此時(shí)p q都是地址,這句換相當(dāng)于前面的幾行取消掉,改為swap(&a,&b)
     //因此,指針的函數(shù)調(diào)用用的是地址作為變量
printf ("max = %d  min =%d\n",a,b);

return 0;
}
2.....換地址不換值
   用函數(shù)形式,不可以這樣,只可以直接進(jìn)行互換
  
// 不可能通過(guò)執(zhí)行調(diào)用函數(shù)來(lái)改變實(shí)參指針變量的值,但是可以改變實(shí)參指針變量所指變量的值
//  所以這個(gè)不可以進(jìn)行函數(shù),只可以直接進(jìn)行寫
#include<stdio.h>
void swap (int * p, int * q)
{
int * temp;
temp = p;
p = q;
q = temp;
}
int main (void)
{
int a, b;
scanf ("%d %d",&a,&b);
if (a
  swap(&a,&b);

printf ("max = %d  min =%d\n",a,b);
return 0;
}






歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1