This is for an iOS project. I am reworking a section of my dataController to use a 2D C array rather than nested NSMutableArrays for speed optimization. I am finding I need to perform thousands of integer addition operations on various sections of the array, and the object model is rather slow.
My array dimension is currently 710 x 55, the 710 number being dynamic. I also have 5 other arrays of the same size, possibly more in the future, hence my need to avoid NSArrays.
I wont post the entire source, so just the relevant parts:
@implementation MMEventDataController
int **wbOcMatrix = NULL;
int numEvents = 0;
-(void)generateMatrix {
for (NSDictionary *item in JSONData) {
{...}
// Here I parse some JSON data and bring part of it into newEvents.wb which is an
// NSMutableArray of ints. These can be ints 1 thru 55, which represent various
// flags that can be set. Only 5 flags will be inside each newEvent.wb.
{...}
// Create some empty C arrays. This part is probably where I go wrong.
wbOcMatrix = (int **) realloc (wbOcMatrix, (numEvents+1) * sizeof(int *));
wbOcMatrix[numEvents] = malloc (55 * sizeof(int));
int wbOcArray[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
// Here we find which 5 flags are set in newEvent.wb and set the corresponding index of
// wbOcArray to 1.
for (id object in newEvent.wb) {
int v = wbOcArray[[object intValue]-1];
v++;
wbOcArray[[object intValue] -1] = v;
}
// Then we bring the new wbOcArray into the next index of the wbOcMatrix and increment.
wbOcMatrix[numEvents] = wbOcArray;
numEvents++;
}
// This process repeats for all items in the JSON data, at the moment is 710, thus
// creating an array 710 x 55.
The 2D array seems to be created well, meaning I have array of the proper size with data in it, HOWEVER, each row of the array contains the same data! And that data is from iteration 710.
My suspicion is that since my array is an array of pointers, each iteration is altering the data at the original pointer, and all rows point to the same place. So how can I allocate new memory space for each iteration? I thought that’s what the malloc was for…
You problem is here:
This will free automatically when the loop is over. If you just put a
NSLog(@"%p", wbOcArray);directly after the above line, you will see, that its always pointing to the same address.Replace this line with:
Best,
Christian