C++ 传递指针给函数
C++允许你传递一个指针给函数。为此,只需将函数参数声明为指针类型。
以下是一个简单的示例,我们将一个无符号长整型指针传递给一个函数,并在函数内部改变该值,这将在调用函数中反映出来 –
#include <iostream>
#include <ctime>
using namespace std;
void getSeconds(unsigned long *par);
int main () {
unsigned long sec;
getSeconds( &sec );
// print the actual value
cout << "Number of seconds :" << sec << endl;
return 0;
}
void getSeconds(unsigned long *par) {
// get the current number of seconds
*par = time( NULL );
return;
}
当上述代码被编译和执行时,它会产生以下结果 –
Number of seconds :1294450468
能够接受指针的函数也可以接受数组,如下面的示例所示:
#include <iostream>
using namespace std;
// function declaration:
double getAverage(int *arr, int size);
int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg << endl;
return 0;
}
double getAverage(int *arr, int size) {
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = double(sum) / size;
return avg;
}
当上述代码被编译和执行时,会产生以下结果-
Average value is: 214.4