views:

822

answers:

2

I am working with C style 2d arrays of integers.

This is fine in my main class file, and I can pass my arrays by reference to other classes. I have run into issues when I try to retrieve a pointer to the arrays and work with that.

My question is: rather than using C style 2d arrays, is there a better way to do it? maybe a Cocoa class I don't know about? I noticed NSMatrix, but that seems geared for cells, rather than plain ints.

I've got calls all over the place in this format: items[x][y], so a shorthand way of referencing array positions would be great.

Further details:

I set up the arrays as instance variables, and tried to access like this:

-(void) setItems: (int [15][24])items { (*pitems)[24] = **items; }

-(int) getItems { return (*pitems)[24]; }

When I tried to retrieve using getItems, I was getting compiler warnings about creating a reference without a cast.

+2  A: 

An interesting discussion here: http://www.idevapps.com/forum/archive/index.php/t-244.html

Basically the suggestion was to turn your 2D array into multiple 1D arrays. For Example:

int array[20][8] becomes

int** array = (int*)malloc(20 * sizeof(int*));

unsigned int i = 0;
for (i = 0; i < 20; ++i)
{
    array[i] = (int)malloc(8 * sizeof(int));
}

and your method returns int** and variable is of type int**.

This has the advantage that normal 2D array indexing works as expected.

The other option that wasn't suggested in the link was to use a NSMutableArray of type NSMutableArray. This would be slower than standard C arrays, but easier to pass around and reference.

KiwiBastard
Thanks. So in this case I could return a **int pointer, but then I do something like this (to point the returned pointer to an array):int items[15][24] = [object getArray]; ?If not, how do I access the returned array?
deadcat
+1  A: 

You can only pass around 2D static arrays if you know the exact size of the first dimension:

// OK, even though we don't know the size of the second dimension
- (void) doStuff: (int [15][])array { ... }
...
int array[15][24];
[self doStuff:array];

// ERROR: don't know size of first dimension (second dimension is irrelevant)
- (void) doStuff: (int [][])array { ... }

Of course, then your function only works for one particular array size in the first dimension. If you won't know the size if your first dimension until runtime, you'll have to either flatten your array into a 1D array, or use a dynamically allocated array of pointers to 1D arrays as in KiwiBastard's answer.

Adam Rosenfield