在Objective C中传递一个可变长度的int数组作为函数参数 [英] Passing an int array of variable length as a function parameter in Objective C
问题描述
int testarr [3] [3] = {
{1,1,1},
{1,0,1},
{1,1,1}
};
[self testCall:testarr];
调用这个函数:
<$ p $ (无效)testCall:(int [3] [3])arr {
NSLog(@cell value is%u,arr [1] [1 ]);
}
我需要数组的长度是可变的 - 什么是最好的方法声明函数?
使用空格不起作用:
- (void)testCall:(int [] [])arr {
感谢您的帮助。 / p>
我会把它写成:
- (void)testCall:(int *)aMatrice;
这样做可以避免使用多个malloc和数学来计算线性数组中的单个偏移量在二维数组中的x,y坐标是微不足道的。它还避免了int **所蕴含的多重malloc以及由语言延续的二维数组语法的局限性。
因此,如果你想要一个4x5的数组,你可以做:
#define WIDTH 4
#define HEIGHT 5
#define INDEXOF(x,y)( (y * WIDTH)+ x)
int * myArray = malloc(sizeof(int)* 5 * ELEMS_PER_ROW);
然后,您可以线性初始化数组或使用嵌套for循环: $ b $ (int y = 0; y
for(int x = 0; x
您可以将它传递给像这样的方法:
[foo testCall:myArray];
尽管您可能也想要携带宽度和高度,但更好的方法是创建一个IntMatrix
(所有代码都输入到SO中)
是一个NSObject的子类,它包含了所有指针算术和存储。
I have the following code which works fine...
int testarr[3][3] = {
{1,1,1},
{1,0,1},
{1,1,1}
};
[self testCall: testarr];
Which calls this function:
- (void)testCall: (int[3][3]) arr {
NSLog(@"cell value is %u",arr[1][1]);
}
I need the array to be of variable length - What is the best way to declare the function?
Using blanks doesn't work:
- (void)testCall: (int[][]) arr {
Thanks for your help.
I would write this as:
- (void) testCall: (int *) aMatrice;
Doing so allows you to avoid multiple mallocs and the math to calculate a single offset in a linear array based on x, y coordinates in a 2D array is trivial. It also avoids the multiple mallocs implied by int** and the limitations of 2D array syntax perpetuated by the language.
So, if you wanted a 4x5 array, you might do:
#define WIDTH 4
#define HEIGHT 5
#define INDEXOF(x,y) ((y*WIDTH) + x)
int *myArray = malloc(sizeof(int) * 5 * ELEMS_PER_ROW);
You could then initialize the array linearly or with a nested for loop:
for(int x=0; x<width; x++)
for(int y=0; y<height; y++)
myArray[INDEXOF(x,y)] = ... some value ...;
And you would pass it to the method like:
[foo testCall: myArray];
Though you might want to also carry along the width and the height or, better yet, create a IntMatrix subclass of NSObject that wraps all of the pointer arithmetic and storage beyond a nice clean API.
(all code typed into SO)
这篇关于在Objective C中传递一个可变长度的int数组作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!