學了C C++老久了,有些基本的用法必須注意,強化在心中,避免每次用的時候再去查書。比如數組作為函數參數& 指針作為函數參數的問題,今天加深了一下!
【例】寫一個函數max_min(),作用:從一個數組a[N],從a[N]中找出最大值和最小值:
void max_min(const int *a, const int N, int* max, int* min)
{
*max = *min = a[0];
int i;
for (i = 1; i < N; i++)
{
if (*max < a[i])
*max = a[i];
if (*min > a[i])
*min = a[i];
}
}
在這個例子中要注意兩個點:
1. 數組作為函數參數
void max_min(const int *a, constint N…)
也可以寫成 void max_min(const int a[], const int N…)
主函數中相應的代碼:
int xc[4]
for (i = 0; i<4; i++)
{
xc[i]= ;/*****代碼初始化*****/
}
int x_max, x_min,;
max_min(xc, 4, &x_max,&x_min);
可以看到,調用形式即max_min(xc, 4,…)
2. 指針作為函數參數
這個問題在很久以前學習C語言的時候就遇到過,并且專門作為一個難點來學習,記得當時所舉的例子就是交換兩個變量的值的問題。
在上面的例子中同樣,也是這個問題。
max_min函數沒有反回值,但是我們要得到的最大最小值通過max,min兩個參數傳回主函數中,這裡就必須用位址或指針的方式來完成:
void max_min(…, int *max, int *min)
在主函數中,見上面的代碼最後一行,用取位址符來調用:max_min(…, &x_max, &x_min);