内存相关崩溃:Cocos2d游戏中的3维数组

问题描述 投票:0回答:1

这是代码:

.h中的声明

@interface LevelManager : NSObject{

}
@property int ***construtorDeMundo;

初始化和malloc

-(id)init {
    self = [super init];
    if(self != nil){
        construtorDeMundo = (int***) malloc ( NUMFASES * sizeof(int *));

        for (int i = 0; i < NUMFASES ; i++) {
            construtorDeMundo[i] = (int**) malloc (MAX_PONTOS_CRITICOS * sizeof(int));
        }

        for (int i = 0; i < NUMFASES; i++)
            for (int j = 0; j < MAX_PONTOS_CRITICOS; j++) {
                construtorDeMundo[i][j] = (int*) malloc (PROPRIEDADES * sizeof(int));
                for (int k = 0; k < PROPRIEDADES ; k++)
                    construtorDeMundo[i][j][k] = 0;
            }

        [self pegaInformacoes];
    }
    return self;
}

访问代码:

 for (int j = 1; j < [elements count]; j++) {
            if(j <= PROPRIEDADES+1){
                NSString *valor = (NSString *)[elements objectAtIndex:j];
                construtorDeMundo[fase][i][j-1] = [((NSNumber*)valor) intValue];
            }
        }

游戏在最后一个函数中随机崩溃以获得不同的索引。与malloc有关的东西......如何解决?如果你知道,请帮助我。

对不起,这个游戏代码不是英文的...不是我写的。

提前致谢。

c++ c iphone xcode cocos2d-iphone
1个回答
0
投票

最后修复了问题。在上面的代码中,为sizeof()提供了错误的值。

这是更新的代码:

-(id)init {
    self = [super init];
    if(self != nil){
        construtorDeMundo = (int***) malloc ( (NUMFASES) * sizeof(*construtorDeMundo));

        for (int i=0; i < NUMFASES; ++i)
            construtorDeMundo[i] = NULL;

        for (int i = 0; i < NUMFASES ; ++i) {
            construtorDeMundo[i] = (int**) malloc (MAX_PONTOS_CRITICOS * sizeof(*construtorDeMundo[i]));
        }

        for (int i=0; i < NUMFASES; ++i)
            for (int j=0; j < MAX_PONTOS_CRITICOS; ++j)
                construtorDeMundo[i][j] = NULL;

        for (int i = 0; i < NUMFASES; ++i)
            for (int j = 0; j < MAX_PONTOS_CRITICOS; ++j) {
                construtorDeMundo[i][j] = (int*) malloc ((PROPRIEDADES) * sizeof(*construtorDeMundo[i][j]));
                for (int k = 0; k < PROPRIEDADES ; k++)
                    construtorDeMundo[i][j][k] = 0;
            }


        [self pegaInformacoes];
    }
    return self;
}
© www.soinside.com 2019 - 2024. All rights reserved.