C語言指針應用簡單實例。本站提示廣大學習愛好者:(C語言指針應用簡單實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C語言指針應用簡單實例正文
作者:楊鑫newlfe
這篇文章主要介紹了C語言指針應用簡單實例的相關資料,需要的朋友可以參考下C語言指針應用簡單實例
這次來說交換函數的實現:
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;
}
//沒錯你的結果如下,發現沒有交換成功,
//是因為你這裡你只是把形參的兩個變量交換了,
//然後函數執行完畢後你就把資源釋放了,而沒有實際改變實參。
那麼用指針實現:
#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;
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!