Header Ads

Return array from function - objective C

Objective C programming language does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

If you want to return a single dimensional array from a function, you would have to declare a function returning a pointer as in the following example:

int * myFunction ()
{
.
.
}

Second point to remember is that objective C does not advocate 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 and call this function as follows:




#import <Foundation/Foundation.h>

@interface SampleClass : NSObject

- (int *) getRandom;
@end

@implementation SampleClass
                  

                   //function to generate and return random numbers
- (int *) getRandom{
    

    static int r[10];
    int i;


    
   //set the seed
    srand (unsigned) time(NULL));

    for(  = 0; i<10; ++i)
    {

             r[i] = rand();
             NSLog(@"r[%d] =%d\n", i ,r[i]);
    }
    return r;
}
 @end

int main()
{
     // an int array with 5 element
     int *p;

     int i;

     SampleClass obj = [SampleClass alloc]init];
   

   p = [obj getRandom];
 

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

   return 0;



No comments:

Powered by Blogger.