无法在obj-c项目中初始化动态2d c数组

时间:2012-05-20 06:51:49

标签: objective-c arrays 2d malloc

这适用于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.

我怀疑是因为我的数组是一个指针数组,每次迭代都会改变原始指针的数据,所有行都指向同一个地方。那么如何为每次迭代分配新的内存空间呢?我认为这就是malloc的用途......

1 个答案:

答案 0 :(得分:0)

你的问题在这里:

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;

最佳, 基督教