Passing an int array of variable length as a function parameter in Objective C

前端 未结 5 1682
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 13:04

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 c

5条回答
  •  抹茶落季
    2021-01-12 14:10

    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

    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)

提交回复
热议问题