【发布时间】:2014-01-13 10:46:24
【问题描述】:
维护iOS应用程序的一些代码,我遇到了以下问题:
CLLocationCoordinate2D inputArray[size]; // CLLocationCoordinate2D is a struct containing two doubles
for (int i = 0; i < size; i++) {
inputArray[i] = ... ; // Fill the array
}
CLLocationCoordinate2D outputArray[size];
functionThatConvertsInputToOutput(inputArray, outputArray, size);
这里我们正在分配两个动态大小的结构数组(无法在编译时确定大小)。所谓的“可变长度数组”,基于那个 SO 问题 (Declare Dynamic Array)。
我很清楚这甚至不能在 C/C++ 中编译,并且在处理类似问题时,答案通常是“使用 malloc”或“使用 NS(Mutable)Array”。
但我还没有真正找到问题的答案:
在声明 int array[size]; 时,Objective C 中会发生什么?
我想知道的原因是,我在上面复制的这段代码在使用具有相当大尺寸 (36000) 的 VLA 时会崩溃,而在使用 malloc 时不会崩溃:
CLLocationCoordinate2D *inputArray = malloc(sizeof(CLLocationCoordinate2D) * size);
CLLocationCoordinate2D *ouputArray = malloc(sizeof(CLLocationCoordinate2D) * size);
编辑#1:维基百科对 VLA http://en.wikipedia.org/wiki/Variable-length_array 的评价
编辑#2:崩溃是EXC_BAC_ACCESS 在functionThatConvertsInputToOutput 的奇怪位置或在调用functionThatConvertsInputToOutput 的线路上。
【问题讨论】:
-
Objective-C 是基于 C 的,所以它在 C 和 Objective-C 中被支持。如果您不喜欢它(我不喜欢),请使用
malloc()和朋友。 -
那不是我不喜欢它。只是,我似乎在使用 VLA 时遇到了与溢出相关的崩溃,我真的不明白为什么。
-
我认为 Wil Shipley 已经回答了这个问题。
-
没错 :) 谢谢!
标签: ios objective-c arrays cocoa