开发者

2D Dynamic Memory Allocation - ObjectiveC

开发者 https://www.devze.com 2023-01-28 03:43 出处:网络
I need some examples of dynamic memory allocation of 2D array in ObjectiveC in iPhone sdk. Sample code 开发者_如何学Cwill be appreciated. I want to declare an array of pointers and then each index wil

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

Thanks


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).


Umm of course C has dynamic memory allocation. Look at malloc and realloc. With this you can allocate memory and resize later if needed, you just have to keep track of all your memory usage and don't forget to free() when you are done.


For NSArrays, You can use something like this:

NSMutableArray *array2d = [[NSMutableArray alloc] init];
for (int i = 0; i < d1; i++)
{
      NSMutableArray *innerArray = [NSMutableArray array];
      [array2D addObject:innerArray];

      for (int j = 0; j < d2; j++)
      {
           [innerArray addObject:myDynamicData];
      }
}

If you mean something else by dynamic data, then please edit the OP explaining exactly what you mean.

0

精彩评论

暂无评论...
验证码 换一张
取 消