【问题标题】:functions calling from main method objective c从主方法目标 c 调用的函数
【发布时间】:2014-10-30 14:14:22
【问题描述】:

这里我需要编写一个从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);
}

提前谢谢....

【问题讨论】:

  • 预期输出是什么?

标签: objective-c function main-method


【解决方案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]) 有效。 Quoted From Another Question

【讨论】:

  • 请告诉它是否有必要在 main 函数之前声明 void displayit (int array[], int len) 以及为什么要添加 void。
  • 如果你没有在 main 之前声明函数,你会得到以下错误(或警告)。这是 C 的规则,Objective-C 也遵循它。 ///Users/Sinri/Codes/WebProjects/overstack/OSTEST/OSTEST/main.m:17:9:函数“displayit”的隐式声明在 C99 中无效 ///Users/Sinri/Codes/WebProjects/overstack/OSTEST /OSTEST/main.m:22:6: 'displayit' 的类型冲突 ///Users/Sinri/Codes/WebProjects/overstack/OSTEST/OSTEST/main.m:17:9: 以前的隐式声明在这里
  • 还有什么需要检查的?
  • 我想在函数中传递一个数组并在输出中返回数组...无法发布我的代码你能不能给任何 email_id 或聊天 ID 来询问它非常有帮助...
  • “返回”是什么意思?是否要在函数中包含return array;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多