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:
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 4×5 array, you might do:
You could then initialize the array linearly or with a nested for loop:
And you would pass it to the method like:
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)