C語言指針應(yīng)用簡單實例
更新時間:2017年05月10日 16:46:28 作者:楊鑫newlfe
這篇文章主要介紹了C語言指針應(yīng)用簡單實例的相關(guān)資料,需要的朋友可以參考下
C語言指針應(yīng)用簡單實例
這次來說交換函數(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;
}
//沒錯你的結(jié)果如下,發(fā)現(xiàn)沒有交換成功,
//是因為你這里你只是把形參的兩個變量交換了,
//然后函數(shù)執(zhí)行完畢后你就把資源釋放了,而沒有實際改變實參。

那么用指針實現(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語言的代碼里
//使用這種引用的方式就會報錯。
#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;
}

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
C++的try塊與異常處理及調(diào)試技術(shù)實例解析
這篇文章主要介紹了C++的try塊與異常處理及調(diào)試技術(shù)實例解析,有助于讀者加深對try塊調(diào)試技術(shù)的認(rèn)識,需要的朋友可以參考下2014-07-07

