创建一个整数数组,其大小基于NSArray的大小 [英] Creating an array of ints whose size is based on the size of an NSArray
问题描述
我正在尝试根据运行时获得的大小创建 int
s数组并将其清零:
I'm trying to create and zero an array of int
s 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;
大小
和索引
都是此类的空子。
int size;
int* indexes;
不过,我最终得到了一个0长度的数组。如何使用 [gamePiece.availableMoves.moves count]
指示的大小创建它?
I end up with a 0-length array, though. How can I create it with the size indicated by [gamePiece.availableMoves.moves count]
?
推荐答案
首先,您无法执行正在执行的操作。即使这可行,当方法返回并删除当前堆栈框架时,数组也将消失。您需要动态分配数组,然后需要记住在释放对象时释放它。因此:
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));
然后,在您的-[dealloc]
方法:
if( indexes ) free(indexes);
使用calloc(3)可以确保将所有内存清零,因此您不需要调用memset(3)。
Using calloc(3) will ensure that all the memory is zeroed out, so you don't need to call memset(3).
这篇关于创建一个整数数组,其大小基于NSArray的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!