在 obj-c 项目中初始化动态 2d c 数组时出现问题



这是针对iOS项目的。我正在重新设计我的dataController的一部分,以使用2D C阵列而不是嵌套的NSMutableArrays来优化速度。我发现我需要对数组的各个部分执行数千个整数加法操作,并且对象模型相当慢。

我的数组尺寸当前为 710 x 55,710 数字是动态的。我还有 5 个相同大小的其他数组,将来可能会更多,因此我需要避免 NSArrays。

我不会发布整个源代码,所以只发布相关部分:

@implementation MMEventDataController
int **wbOcMatrix = NULL;
int numEvents = 0;
-(void)generateMatrix {
for (NSDictionary *item in JSONData) {
{...}
// Here I parse some JSON data and bring part of it into newEvents.wb which is an
// NSMutableArray of ints. These can be ints 1 thru 55, which represent various
// flags that can be set. Only 5 flags will be inside each newEvent.wb. 
{...}
// Create some empty C arrays. This part is probably where I go wrong.
    wbOcMatrix = (int **) realloc (wbOcMatrix, (numEvents+1) * sizeof(int *));
    wbOcMatrix[numEvents] = malloc (55 * sizeof(int));
    int wbOcArray[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

// Here we find which 5 flags are set in newEvent.wb and set the corresponding index of
// wbOcArray to 1.
    for (id object in newEvent.wb) {
        int v = wbOcArray[[object intValue]-1];
        v++;
        wbOcArray[[object intValue] -1] = v;
        }
// Then we bring the new wbOcArray into the next index of the wbOcMatrix and increment.
    wbOcMatrix[numEvents] = wbOcArray;
    numEvents++;
}
// This process repeats for all items in the JSON data, at the moment is 710, thus
// creating an array 710 x 55.

2D 数组似乎创建得很好,这意味着我有适当大小的数组,其中包含数据,但是,数组的每一行都包含相同的数据!这些数据来自迭代710。

我的

怀疑是,由于我的数组是一个指针数组,因此每次迭代都会更改原始指针处的数据,并且所有行都指向同一位置。那么如何为每次迭代分配新的内存空间呢?我以为这就是马洛克的用途...

你的问题在这里:

int wbOcArray[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

这将在循环结束时自动释放。如果你只是在上面一行后面直接放一个NSLog(@"%p", wbOcArray);,你会看到它总是指向同一个地址。

将此行替换为:

int* wbOcArray = (int*)malloc(sizeof(int)*55);
for(int i = 0; i < 55; i++) wbOcArray[i] = 0;

最好基督教

最新更新