C語(yǔ)言指針應(yīng)用簡(jiǎn)單實(shí)例
這次來(lái)說(shuō)交換函數(shù)的實(shí)現(xiàn):
1、
#include <stdio.h> #include <stdlib.h> void swap(int x, int y) { int temp; temp = x; x = y; y = temp; } int main() { int a = 10, b = 20; printf("交換前:/n a = %d, b = %d/n", a, b); swap(a, b); printf("交換后:/n a = %d, b = %d", a, b); return 0; } //沒錯(cuò)你的結(jié)果如下,發(fā)現(xiàn)沒有交換成功, //是因?yàn)槟氵@里你只是把形參的兩個(gè)變量交換了, //然后函數(shù)執(zhí)行完畢后你就把資源釋放了,而沒有實(shí)際改變實(shí)參。
那么用指針實(shí)現(xiàn): #include <stdio.h> #include <stdlib.h> void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } int main() { int a = 10, b = 20; printf("交換前:/n a = %d, b = %d/n", a, b); swap(&a, &b); printf("交換后:/n a = %d, b = %d", a, b); return 0; } 
//還有一種方式就是“引用 ”如下的sawp(&a, &b) //這里是c++的代碼,如果你在c語(yǔ)言的代碼里 //使用這種引用的方式就會(huì)報(bào)錯(cuò)。 #include <cstdio> #include <iostream> using namespace std; void swap(int &x, int &y) { int temp; temp = x; x = y; y = temp; } int main() { int a = 10, b = 20; printf("交換前:/n a = %d, b = %d/n", a, b); swap(a, b); printf("交換后:/n a = %d, b = %d", a, b); return 0; } 
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選