Passing Arrays as Function Arguments - objective C
If you want to pass a single- dimensional array as an argument in a function, you would have to declare function formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received. Similar way, you can pass multi-dimensional array as formal parameter.
Way 1
Formal parameters as a pointer as follows.
Way 2
Way 3
Formal parameters as an unsized array as follows:
Example
Now consider the following function, which will take an array as argument along with another argument and based on the passed argument, it will return average of the numbers passed through the array as follows:
Now let us call the above function as follows:
As you can see, the length of the array doesn't matter as far as the function is concerned because objective C performs no bounds checking for the formal parameters.
Way 1
Formal parameters as a pointer as follows.
- (void) mufuncion (int *)param
{
.
.
}
{
.
.
}
Way 2
- (void) myfunction (int [10]) param
{
.
.
}
{
.
.
}
Way 3
Formal parameters as an unsized array as follows:
- (void) myfunction : ( int [] ) param
{
.
.
}
{
.
.
}
Example
Now consider the following function, which will take an array as argument along with another argument and based on the passed argument, it will return average of the numbers passed through the array as follows:
- (double) getaverage : (int []) arr andSixe : (int) size
{
int i;
double avg;
double sum;
for(i = 0; i<size; ++i)
{
sum += arr[i];
}
avg = sum / size;
return avg;
}
{
int i;
double avg;
double sum;
for(i = 0; i<size; ++i)
{
sum += arr[i];
}
avg = sum / size;
return avg;
}
Now let us call the above function as follows:
As you can see, the length of the array doesn't matter as far as the function is concerned because objective C performs no bounds checking for the formal parameters.
No comments: