Best way to work with array of pointers in Objective-C?

I am trying to reproduce the following Java code:

int[][] multi; // DIMENSIONS ARE UNKNOWN AT CREATION TIME
// LATER ON...
multi = new int[10][];
multi[5] = new int[20];
multi[5][11] = 66;
// LATER ON...
multi = null; // PROPER WAY OF FREEING EVERYTHING

      

I came out with the following Objective-C version:

int* *multi;
//
multi = malloc(10 * sizeof(int*));
multi[5] = (int *) malloc(20 * sizeof(int));
multi[5][11] = 66;
//
free(multi[5]);
free(multi);

      

So firstly, I would like to hear if this is the best way to go. And basically: I can't find a way to free memory in some "automatic" way, i.e. The following code throws runtime exceptions on the IPhone:

for (int i = 0; i < 10; i++)
{
    if (multi[i] != NULL) free(multi[i]);
}

      

+1


source to share


3 answers


Free does not zero out the memory address in the pointer, it just cancels it. Thus, if you use this loop more than once, you will get exceptions when you try to free memory that has already been invalidated. You can use NSPointerArray or wrap integers in objects and use NSMutableArray for your purposes, but if you just want to use what you have and you use the loop more than once, you will need to do something like:

int **multi;
multi = calloc(10, sizeof(int*));
multi[5] = calloc(20, sizeof(int));
//
multi[5][11] = 66;
//
for( int i = 0; i < 10; i++ ) {
  if( multi[i] ) {
    free(multi[i]);
    multi[i] = NULL;
  }
}
//
free(multi);

      



This way, if the loop has been run more than once, you won't fail. Also, I am using calloc instead of malloc because it will set all pointers to NULL and integers to 0. The first parameter is the size of the array you want (in your case) and the second parameter is the size of the type (so no multiplication is required).

+7


source


First, the proposed solution in the question is not specific to Objective-C, it is the C standard. The C translation of the Java code looks correct.

Second, the proposed "automatic" free one cannot work: malloc () does not initialize the allocated memory. I would use calloc () instead, or add memset () after malloc ().



Third, for the Objective-C version, I would consider an NSMutableArray object populated with NSMutableArray objects populated with NSNumber objects. For your purpose, I believe the C version is ok.

+3


source


You can create a one-dimensional array and then use an index based on your two values. This way will have less initialization code to deal with.

Also, if you defer initialization multi

until you know the dimensions, you can simply initialize it as if it were a static array, not a variable size.

0


source







All Articles