创建一个整数数组,其大小基于 NSArray 的大小
我正在尝试根据运行时获得的大小创建一个 int
数组并将其归零:
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
和 indexes
都是 ivars此类的:
int size;
int* indexes;
不过,我最终得到了一个 0 长度的数组。如何使用 [gamePiece.availableMoves.moves count]
指示的大小创建它?
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;
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]
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,你不能做你正在做的事情。即使这样有效,当方法返回并且当前堆栈帧被删除时,数组也会消失。您需要动态分配数组,然后需要记住在释放对象时释放它。所以:
然后,在您的
-[dealloc]
方法中:使用 calloc(3) 将确保所有内存都清零,因此您不需要调用 memset(3)。
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:
Then, in your
-[dealloc]
method:Using calloc(3) will ensure that all the memory is zeroed out, so you don't need to call memset(3).
数组大小应该是常量整数表达式。您需要使用malloc。
现在,您可以正常通过索引运算符
[]
访问元素。Array size should be a constant integral expression. You need to use malloc.
Now, you can normally access elements by index operator
[]
.