在Objective C中传递一个可变长度的int数组作为函数参数

7 arrays parameters function objective-c

我有以下代码,工作正常...

int testarr[3][3] = {
  {1,1,1},
  {1,0,1},
  {1,1,1}
};   
[self testCall: testarr];
Run Code Online (Sandbox Code Playgroud)

哪个叫这个功能:

- (void)testCall: (int[3][3]) arr {

    NSLog(@"cell value is %u",arr[1][1]);
}
Run Code Online (Sandbox Code Playgroud)

我需要数组的长度可变 - 声明函数的最佳方法是什么?

使用空格不起作用:

- (void)testCall: (int[][]) arr { 
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

bbu*_*bum 6

我会这样写:

- (void) testCall: (int *) aMatrice;
Run Code Online (Sandbox Code Playgroud)

这样做可以避免多个mallocs和数学来计算基于x,y坐标的线性数组中的单个偏移量在2D数组中是微不足道的.它还避免了int**隐含的多个mallocs以及该语言延续的2D数组语法的局限性.

所以,如果你想要一个4x5阵列,你可能会这样做:

#define WIDTH 4
#define HEIGHT 5
#define INDEXOF(x,y) ((y*WIDTH) + x)

int *myArray = malloc(sizeof(int) * 5 * ELEMS_PER_ROW);
Run Code Online (Sandbox Code Playgroud)

然后,您可以线性地或使用嵌套for循环初始化数组:

for(int x=0; x<width; x++)
    for(int y=0; y<height; y++)
        myArray[INDEXOF(x,y)] = ... some value ...;
Run Code Online (Sandbox Code Playgroud)

你会把它传递给像这样的方法:

[foo testCall: myArray];
Run Code Online (Sandbox Code Playgroud)

虽然您可能还希望同时携带宽度和高度,或者更好的是,创建一个NSObject的IntMatrix子类,它将所有指针算术和存储包装在一个漂亮的干净API之外.

(所有代码都输入SO)