Search code examples
objective-cfunctionmain-method

functions calling from main method objective c


Here I need to write a function which is called from main method with integer array as a parameter please give me example.

In below example parameter are int type.

Note : please tell this is correct way to do this or not...

#import <Foundation/Foundation.h>

void displayit (int);

int main (int argc, const char * argv[])
{
    @autoreleasepool {
        int i;

        for (i=0; i<5; i++)
        {
                displayit( i );
        }

   }
   return 0;
}

void displayit (int i)
{
        int y = 0;

        y += i;

        NSLog (@"y + i = %i", y);
}

Thanks in advance....


Solution

  • I tried out these, please check.

    #import <Foundation/Foundation.h>
    
    void displayit (int array[], int len);
    
    int main (int argc, const char * argv[])
    {
        @autoreleasepool {
            int array[]={1,2,3};
            displayit( array, 3 );
        }
        return 0;
    }
    
    void displayit (int array[], int len)
    {
        for(int i=0;i<len;i++){
            NSLog(@"display %d : %d",i,array[i]);
        }
    }
    

    The out put is:

    2014-10-30 14:09:32.017 OSTEST[32541:77397] display 0 : 1
    2014-10-30 14:09:32.018 OSTEST[32541:77397] display 1 : 2
    2014-10-30 14:09:32.018 OSTEST[32541:77397] display 2 : 3
    Program ended with exit code: 0
    

    I used another parameter len to avoid boundary beyond.

    If the array is a global, static, or automatic variable (int array[10];), then sizeof(array)/sizeof(array[0]) works. Quoted From Another Question