Search code examples
objective-ccpointersdynamic-arrays

Creating an array of ints whose size is based on the size of an NSArray


I'm trying to create and zero an array of ints based on a size that I get at runtime:

size = [gamePiece.availableMoves.moves count]; //debugger shows size = 1;
int array[size]; //debugger shows this as int[0] !
memset(array, 0, size);
indexes = array;

size and indexes are both ivars of this class:

int size;
int* indexes;

I end up with a 0-length array, though. How can I create it with the size indicated by [gamePiece.availableMoves.moves count]?


Solution

  • First of all, you can't do what you're doing. Even when this works, the array is going to disappear when the method returns and the current stack frame is removed. You need to dynamically allocate the array, then you need to remember to free it when your object is deallocated. So:

    size = [gamePiece.availableMoves.moves count];
    indexes = calloc(size, sizeof(int));
    

    Then, in your -[dealloc] method:

    if( indexes ) free(indexes);
    

    Using calloc(3) will ensure that all the memory is zeroed out, so you don't need to call memset(3).