Assignment of the 2D dynamic memory - Objective C


I need some examples of dynamic memory allocation of 2D array in ObjectiveC in iPhone sdk. Sample code will be appreciated. I want to declare an array of pointers and then each index will be declare an array at runtime.


It is weird to collude C arrays and NSArrays, but it can be done:

NSMutableArray *myArrays[];
myArrays = malloc(sizeof(NSMutableArray *) * numberOfArrays);

A better solution would either be to use an NSArray of NSArrays;

NSMutableArray *rows = [NSMutableArray array];
[rows addObject: [NSMutableArray array]];
[rows addObject: [NSMutableArray array]];
[rows addObject: [NSMutableArray array]];

NSMutableArray *row0 = [rows objectAtIndex: 0];
[row0 addObject: [Datum new]];
[row0 addObject: [Datum new]];
[row0 addObject: [Datum new]];

.... etc ....

Or, just use an array of pointers directly:

Datum **my2DArray = malloc(sizeof(Datum *) * width * height);

Then, any given cartesian coordinate within my2DArray is a simple bit of math:

my2DArray[ x + (y * width) ] = ....;

That'll effectively convert any given (x,y) coordinate into a linear index (effectively, y becomes the stride and x becomes the offset within the stride).