Search code examples
objective-ciphonearraysios4exc-bad-access

Array giving EXC_BAD_ACCESS in for loop


I have a C array defined in my method as:

int c = 4;
int r = 5;
keysArray[c][r];

I have this for loop, which works, populating the keysArray as expected.

for (int row = 0; row < r; row++) {
    for (int column = 0; column < c; column++){
        keysArray[column][row] = [anotherArray objectAtIndex:0];
        NSLog(@"array1 %@",keysArray[column][row]);
        [anotherArray removeObjectAtIndex:0];
    }
}

Then in a for loop underneath, featuring exactly the same looping counter structure, when i try to NSLog the array, it gives an EXC_BAD_ACCESS.

for (int row = 0; row < r; row++){
    for (int column = 0; column < c; column++) {            
        NSLog(@"array2: %@",keysArray[column][row]); //EXC_BAD_ACCESS here
    }
}

What would cause this to happen, given that the keysArray is defined in the method body, outside of both sets of loops?


Solution

  • You need to retain the objects held in your C array. Unlikes an NS*Array, a C array does not retain on adding to the array.

    However, for a no-holes 2D array like that, I'd just use a single NSMutableArray. Any N-dimensional array can be represented as a line-- as a one dimensional array-- with simple math.

    Namely, to determine the index of an object at (X,Y), use (Y * width) + X).

    The only caveat is that NS*Array does not support "holes". You will need to fill the array row by row. That is, for a 3x4 (3 wide, 4 tall) array, you would fill it in the order 0,0, 1,0, 2,0, 0,1, 1,1, etc...

    Obviously, insert and remove operations will mess up your 2D representation (but they would in an NSMutableArray of NSMutableArrays, too).

    Alternatively, use NSPointerArray as it can have holes.