http://www.runoob.com/cplusplus/cpp-passing-pointers-to-functions.htmlhtml
下面的實例中,咱們傳遞一個無符號的 long 型指針給函數,並在函數內改變這個值:ios
#include <iostream> #include <ctime> using namespace std; void getSeconds(unsigned long *par); int main () { unsigned long sec; getSeconds( &sec ); // 輸出實際值 cout << "Number of seconds :" << sec << endl; return 0; } void getSeconds(unsigned long *par) { // 獲取當前的秒數 *par = time( NULL ); return; }
能接受指針做爲參數的函數,也能接受數組做爲參數,以下所示:數組
#include <iostream> using namespace std; // 函數聲明 double getAverage(int *arr, int size); int main () { // 帶有 5 個元素的整型數組 int balance[5] = {1000, 2, 3, 17, 50}; double avg; // 傳遞一個指向數組的指針做爲參數 avg = getAverage( balance, 5 ) ; // 輸出返回值 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; }