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

南楼画角 提交于 2019-12-12 04:53:23

问题


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]?


回答1:


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).




回答2:


Array size should be a constant integral expression. You need to use malloc.

int *array = malloc( sizeof(int) * size ) ;

Now, you can normally access elements by index operator [].



来源:https://stackoverflow.com/questions/5150312/creating-an-array-of-ints-whose-size-is-based-on-the-size-of-an-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!