4

如何从 Objective-C 方法返回 C 风格的整数数组?这是我的代码到目前为止的样子:

函数调用:

maze = [amaze getMaze];

功能:

-(int*) getMaze{
    return maze;
}

我今天刚开始用 Objective-C 编写,所以这对我来说是全新的。

4

4 回答 4

6

在 C 语言中,如果需要从函数返回数组,则需要使用malloc为其分配内存,然后返回指向新分配内存的指针。

处理完此内存后,您需要释放它。

就像是:

#include <stdlib.h> /* need this include at top for malloc and free */

int* foo(int size)
{
    int* out = malloc(sizeof(int) * size); /* need to get the size of the int type and multiply it 
                                            * by the number of integers we would like to return */

    return out; /* returning pointer to the function calling foo(). 
                 * Don't forget to free the memory allocated with malloc */
}

int main()
{
    ... /* some code here */

    int* int_ptr = foo(25); /* int_ptr now points to the memory allocated in foo */

    ... /* some more code */

    free(int_ptr); /* we're done with this, let's free it */

    ...

    return 0;
}

这就像它得到的 C 风格:) 在 Objective C 中可能有其他(可以说更合适的)方法来做到这一点。但是,由于 Objective C 被认为是 C 的严格超集,这也可以工作。

如果我可以通过指针进一步扩展需要这样做。在函数中分配的 C 样式数组被认为是local,一旦函数超出范围,它们就会被自动清理。

正如另一张海报所指出的,int arr[10];从函数返回标准数组(例如 )是一个坏主意,因为在返回数组时它不再存在。

在 C 中,我们通过使用动态分配内存malloc并返回指向该内存的指针来解决这个问题。

但是,除非您充分释放此内存,否则您可能会引入内存泄漏或其他一些令人讨厌的行为(例如,两次free使用malloc-ed 指针会产生不需要的结果)。

于 2013-06-13T02:42:58.273 回答
4

鉴于您明确询问 C 风格的数组,这里没有您应该使用的建议NSArray等。

不能直接返回一个 C 风格的数组(见下文)作为 Objective-C(或 C 或 C++)中的一个值,你可以返回对这样一个数组的引用。

int等类型都可以按值传递- 即表示值的实际位被传递。其他事情; 比如C风格的数组、动态分配的内存、Objective-C风格的对象等;都是通过引用传递的——这是对内存中某个位置的引用,该位置包含表示值被传递的实际位。doublestruct x

因此,要从函数/方法返回 C 样式数组,您可以:

  1. 动态(malloc )一个数组并返回对分配内存的引用;
  2. 传入现有数组的引用并让函数填充它;或者
  3. 将数组包装为struct...

正常的选择是 (1) 或 (2) - 请注意,您不能返回对堆栈分配数组的引用,如下所示:

int *thisIsInvalid()
{
   int myValues[5];
   ...
   return myValues; // will not work, the type is correct but once function
                    // returns myValues no longer exists.
}

如果您真的想按值返回一个(小)数组,您实际上可以使用 (3) 来完成。请记住,struct值是按值传递的。所以以下将起作用:

typedef struct
{
   int array[5];
} fiveInts;

fiveInts thisIsValid()
{
   fiveInts myValues;
   ...
   myValues.array[3] = ...; // etc.
   ...
   return myValues;
}

(请注意,在读取/写入数组时,将数组包装在 a 中没有任何开销struct- 上面的成本是将所有值复制回来 - 因此只建议用于小型数组!)

高温高压

于 2013-06-13T02:58:54.253 回答
0
- (NSArray *)toArray:(int *)maze {
   NSMutableArray *retVal = [[NSMutableArray alloc] init];
   for (int c = 0; maze[c] != NULL; c++) {
      [retVal addObject:[NSNumber numberWithInt:maze[c]]];
   }
   return [retVal array];
}

我从来都不习惯将可变数据传入和传出方法,也不知道为什么。如果您以后需要更改这些值,请向数组发送一条mutableCopy消息。

于 2013-06-13T02:44:22.203 回答
-1

你可以这样做

- (void)getArray:(int *)array withLength:(NSUInteger)length{
    for (int i = 0; i < length; i++)
        array[i] = i;
}

int array[3];
[object getArray:array withLength:3];
NSLog(@"%d %d %d", array[0], array[1], array[2]);  // 1 2 3
于 2013-06-13T02:52:49.967 回答