1

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....

Nirbhav Gupta
  • 106
  • 2
  • 9

1 Answers1

1

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

Community
  • 1
  • 1
Sinri Edogawa
  • 311
  • 1
  • 6
  • Pls tell its necessary or not to declare void displayit (int array[], int len) before main function and also why you add void. – Nirbhav Gupta Oct 30 '14 at 07:41
  • 1
    If you do not declare the function before main, you would get the following errors(or warnings). It is rule of C, as well followed by Objective-C. ///Users/Sinri/Codes/WebProjects/overstack/OSTEST/OSTEST/main.m:17:9: Implicit declaration of function 'displayit' is invalid in C99 ///Users/Sinri/Codes/WebProjects/overstack/OSTEST/OSTEST/main.m:22:6: Conflicting types for 'displayit' ///Users/Sinri/Codes/WebProjects/overstack/OSTEST/OSTEST/main.m:17:9: Previous implicit declaration is here – Sinri Edogawa Oct 30 '14 at 08:03
  • What's more needs checking? – Sinri Edogawa Oct 30 '14 at 14:00
  • i want to pass an array in function and return array in output...not able to post my code can you given any email_id or chat id to ask its very helpful... – Nirbhav Gupta Oct 30 '14 at 14:07
  • What do you mean the 'return'? Do you want to contain `return array;` in the function? – Sinri Edogawa Oct 30 '14 at 14:11
  • find the code http://stackoverflow.com/questions/26655375/passing-int-array-and-return-array-in-output-using-objective-c – Nirbhav Gupta Oct 30 '14 at 14:15