Objective-C將指標傳遞給函式

2019-10-16 23:15:02

Objective-C程式設計語言允許傳遞指標作為引數給函式。為此,只需將函式的引數宣告為指標型別即可。

下面這個例子中,將一個unsigned long指標傳遞給一個函式並在函式內部的更改引數的值,它反映在呼叫的函式中 -

#import <Foundation/Foundation.h>

@interface SampleClass:NSObject
- (void) getSeconds:(int *)par;
@end

@implementation SampleClass

- (void) getSeconds:(int *)par {
   /* 獲取當前秒數 */
   //*par = time( NULL );
   *par = 111;
   return;
}

@end

int main () {

   int sec=100;

   SampleClass *sampleClass = [[SampleClass alloc]init];
   [sampleClass getSeconds:&sec];

   /* 列印實際的值 */
   NSLog(@"Number of seconds: %d\n", sec );

   return 0;
}

執行上面範例程式碼,得到以下結果:

2018-11-15 06:23:36.731 main[14937] Number of seconds: 111

函式可以接受指標,也可以接受一個陣列,如下例所示 -

#import <Foundation/Foundation.h>

@interface SampleClass:NSObject
/* function declaration */
- (double) getAverage:(int *)arr ofSize:(int) size;
@end

@implementation SampleClass

- (double) getAverage:(int *)arr ofSize:(int) size {
   int    i, sum = 0;       
   double avg;

   for (i = 0; i < size; ++i) {
      sum += arr[i];
   }

   avg = (double)sum / size;
   return avg;
}

@end

int main () {

   /* 定義一個有 5 個元素的陣列 */
   int balance[5] = {99, 92, 93, 87, 90};
   double avg;

   SampleClass *sampleClass = [[SampleClass alloc]init];
   /* 將指標傳遞給陣列作為引數 */
   avg = [sampleClass getAverage: balance ofSize: 5 ] ;

   /* 輸出函式返回結果值  */
   NSLog(@"Average value is: %f\n", avg );

   return 0;
}

執行上面範例程式碼,得到以下結果:

2018-11-15 06:26:49.117 main[134265] Average value is: 92.200000