Passing pointer to function - Objective C
Objective C programming language allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.
Following a simple example where we pass an unsigned long pointer to a function and change the value inside the function which reflects back in the calling function:
The function, which can accept a pointer , can also accept an array as shown in the following example.
avg = [obj getAverage: balance ofSize: 5];
send feedback for improvisation
Following a simple example where we pass an unsigned long pointer to a function and change the value inside the function which reflects back in the calling function:
#import <Foundation/Foundation.h>
@interface SampleClass : NSObject
- (void) getSeconds : (int *) par;
@end
@interface SampleClass : NSObject
- (void) getSeconds : (int *) par;
@end
@implementation SampleClass
- (void) getSeconds : (int *) par
{
*par = time(NULL);
}
@end
int main()
{
SampleClass *obj = [[SampleClass alloc]init];
[obj getSeconds : &sec ];
// print the actual value
NSLog (@:Number of seconds : %d\n", sec);
return 0;
}
The function, which can accept a pointer , can also accept an array as shown in the following example.
#import <Foundation/Foundation.h>
@interface SampleClass : NSObject
- (double) getAverage : (int *) arr ofSize : (int) size;
@end
@interface SampleClass : NSObject
- (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 = sum + arr[i]
}
avg = (double)sum /size;
return avg;
int i, sum = 0;
double avg;
for( i = 0; i <size; i++)
{
sum = sum + arr[i]
}
avg = (double)sum /size;
return avg;
}
@end
int main()
{
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
SampleClass *obj = [[SampleClass alloc]init];
avg = [obj getAverage: balance ofSize: 5];
// print the actual value
NSLog (@"Average of value is : %f\n", avg);
return 0;
}
send feedback for improvisation
No comments: