舉例說明
#include <stdio.h>void swap(int x, int y)
{int temp = 0;temp = x;x = y;y = temp;
}int main(void)
{int a = 1, b = 2;swap(a, b);printf("a=%d, b=%d\n", a, b);return 0;
}
結果為
在函數調用時,a的值傳給x,b的值傳給y。執行完swap函數后,x和y的值是互換了,但main函數中的a和b并未互換。
該例子中a、b為實參,x、y為形參。
函數調用中發生的數據傳送是單向的。即只能把實參的值傳給形參,而不能把形參的值反向地傳給實參。因此在函數調用過程中,形參的值發生改變,而實參中的值不會變化。
形參變量只有在被調用時才分配內存單元,在調用結束時,立刻釋放所分配的內存單元。
?
稍微修改示例代碼
#include <stdio.h>void swap(int *x, int *y)
{int *temp;temp = x;x = y;y = temp;
}int main(void)
{int a = 1, b = 2;int *p1 = &a, *p2 = &b;swap(p1, p2);printf("a=%d, b=%d\n", a, b);return 0;
}
結果仍然是
這也是需要注意的,不能企圖通過改變指針形參的值而使指針實參的值改變。
?
再修改代碼
#include <stdio.h>void swap(int *x, int *y)
{int *temp;*temp = *x;*x = *y;*y = *temp;
}int main(void)
{int a = 1, b = 2;int *p1 = &a, *p2 = &b;swap(p1, p2);printf("a=%d, b=%d\n", a, b);return 0;
}
編譯的時候會出現警告:
運行后會出錯:
因為temp沒有確定的地址值,所指向的單元是不可預見的,它的值也是不可預見的。因此,對*temp賦值可能會破壞系統的正常工作狀況。所以應該用整型變量temp作為臨時輔助變量實現交換功能。
修改代碼如下:
#include <stdio.h>void swap(int *x, int *y)
{int temp = 0;temp = *x;*x = *y;*y = temp;
}int main(void)
{int a = 1, b = 2;int *p1 = &a, *p2 = &b;swap(p1, p2);printf("a=%d, b=%d\n", a, b);return 0;
}
結果為