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
cpp_pointers.htm
廣告