Return pointer from functions in Objective-C

Advertisements


As we have seen in last chapter how Objective-C programming language allows to return an array from a function, similar way Objective-C allows you to return a pointer from a function. To do so, you would have to declare a function returning a pointer as in the following example:

int * myFunction()
{
.
.
.
}

Second point to remember is that, it is not good idea to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.

Now, consider the following function, which will generate 10 random numbers and return them using an array name, which represents a pointer, i.e., address of first array element.

#import <Foundation/Foundation.h>

/* function to generate and return random numbers. */
int * getRandom( )
{
   static int  r[10];
   int i;
 
   /* set the seed */
   srand( (unsigned)time( NULL ) );
   for ( i = 0; i < 10; ++i)
   {
      r[i] = rand();
      NSLog(@"%d\n", r[i] );
   }
 
   return r;
}
 
/* main function to call above defined function */
int main ()
{
   /* a pointer to an int */
   int *p;
   int i;

   p = getRandom();
   for ( i = 0; i < 10; i++ )
   {
       NSLog(@"*(p + [%d]) : %d\n", i, *(p + i) );
   }
 
   return 0;
}

When the above code is compiled together and executed, it produces the result something as follows:

2013-09-13 23:32:30.934 demo[31106] 1751348405
2013-09-13 23:32:30.934 demo[31106] 1361314626
2013-09-13 23:32:30.934 demo[31106] 833264711
2013-09-13 23:32:30.934 demo[31106] 1700550876
2013-09-13 23:32:30.934 demo[31106] 1164219218
2013-09-13 23:32:30.934 demo[31106] 1083527138
2013-09-13 23:32:30.934 demo[31106] 1465344952
2013-09-13 23:32:30.934 demo[31106] 849888001
2013-09-13 23:32:30.934 demo[31106] 1220494938
2013-09-13 23:32:30.934 demo[31106] 2095604466
2013-09-13 23:32:30.934 demo[31106] *(p + [0]) : 1751348405
2013-09-13 23:32:30.934 demo[31106] *(p + [1]) : 1361314626
2013-09-13 23:32:30.934 demo[31106] *(p + [2]) : 833264711
2013-09-13 23:32:30.934 demo[31106] *(p + [3]) : 1700550876
2013-09-13 23:32:30.934 demo[31106] *(p + [4]) : 1164219218
2013-09-13 23:32:30.934 demo[31106] *(p + [5]) : 1083527138
2013-09-13 23:32:30.934 demo[31106] *(p + [6]) : 1465344952
2013-09-13 23:32:30.934 demo[31106] *(p + [7]) : 849888001
2013-09-13 23:32:30.934 demo[31106] *(p + [8]) : 1220494938
2013-09-13 23:32:30.934 demo[31106] *(p + [9]) : 2095604466


Advertisements
Advertisements