0

在这里,我需要编写一个从 main 方法调用的函数,其中整数数组作为参数,请举个例子。

在下面的示例中,参数是 int 类型。

注意:请告诉这是不是正确的方法......

#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);
}

提前致谢....

4

1 回答 1

1

我试过这些,请检查。

#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]);
    }
}

输出是:

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

我使用了另一个参数len来避免超出边界。

如果数组是全局变量、静态变量或自动变量 (int array[10];),则 sizeof(array)/sizeof(array[0]) 有效。引自另一个问题

于 2014-10-30T06:14:22.977 回答