Search code examples
objective-cmultidimensional-arraycalloc

2D arrays in NSPointerArray


I'm creating many 2D int and float C arrays and was going to assign their pointers to NSPointerArray. Everything is fine while I create and populate them with data, but when I do addPointer on array I get EXEC_BAD_ACCESS. Q1-Why this is wrong? Q2-What is the best approach providing access to many 2D arrays created with calloc?

- (NSPointerArray *)treeData{
   if (_treeData == nil) {
      _treeData = [[NSPointerArray alloc] init];
      int** VVD = createIntArray(3000,200); 
      [_treeData addPointer:VVD];
   }
  return _treeData; // addеd later to the post, exists in live code
}

For reference

int** createIntArray(int n, int m)
{    
  int i=0;
   int* values = calloc(m*n, sizeof(int));
   int** rows = malloc(n*sizeof(int*));
   for ( i=0; i<n; ++i)
   {
       rows[i] = values + i*m;
   }
   return rows;

}


Solution

  • the NSPointerArray has to be inited with the right options. by default he tries to RETAIN the pointers passed and as the int** is no NSObject, it crashes. Instead, You have to tell the array to not touch the memory you add! init it with the opaque memory options

    you called just init which is equal to initWithOptions: NSPointerFunctionsStrongMemory
    you have call initWithOptions:NSPointerFunctionsOpaqueMemory

    #import <Foundation/Foundation.h>
    
    int** createIntArray(int n, int m)
    {
        int i=0;
        int* values = calloc(m*n, sizeof(int));
        int** rows = malloc(n*sizeof(int*));
        for ( i=0; i<n; ++i)
        {
            rows[i] = values + i*m;
        }
        return rows;
    }
    
    int main(int argc, char *argv[]) {
        @autoreleasepool {
            id _treeData = [[NSPointerArray alloc] initWithOptions:NSPointerFunctionsOpaqueMemory];
            int** VVD = createIntArray(3000,200);
            [_treeData addPointer:VVD];
        }
    
        NSLog(@"EOF");
    }