Header Ads

Return pointer from function - Objective C

As we have seen in last post how Objective C programming language allows to return an array from 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 to define the local variable as static variable.

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

#import <Foundation/Foundation.h>
  
      - (int ) * getRandom()
        {
               static int r[10];
               int i;
               srand( (unsigned)time (NULL));
              
              for( i =0; i< 10; i++)
              {
                    r[i] = rand();
                   NSLog(@"%d\n", r[i]);
              }
                return r;
         }
int main()
{
     int *p;
     int i ;
     p = getRandom();
    for( i =0 ; i< 10 ; i++)
    {    
              NSLog (@"*(p+ [%d]): %d\n", i , *(p+i) );
     return 0;
}        



No comments:

Powered by Blogger.