2009-02-22 6 views
0

Chaque fois que j'appelle la fonction doSomething, mon programme se bloque. Le code réel comme un peu de vérification des limites de tableau, donc je sais que ce n'est pas un problème.Objective-C: Comment créer une classe avec un tableau 2d C en tant que champ?

maClasse.h

#import <Foundation/Foundation.h> 
@interface myClass : NSObject { 
    BOOL **myMatrix; 

} 
@property(readwrite) BOOL **myMatrix; 

-(myClass*)initWithWidth: (int)w andHeight: (int)h; 
-(void)doSomething; 
+(BOOL **) createMatrixWithHeight: (int)h andWidth: (int)w; 

@end 

myClass.m

#import "myClass.h" 
#import <Foundation/Foundation.h> 

@implementation myClass 

@synthesize myMatrix; 

-(myClass*)initWithWidth: (int)w andHeight: (int)h { 
    self = [super init]; 
    myMatrix = [myClass createMatrixWithHeight: h andWidth: w]; 
    return self; 
} 

-(void)doSomething{ 
    myMatrix[2][2] = YES; 
} 

+(BOOL **) createMatrixWithHeight: (int)h andWidth: (int)w{ 
    BOOL **newMatrix; 

    newMatrix = malloc(w * sizeof(BOOL *)); 

    int i; 
    for(i = 0; i < w; i++){ 
     newMatrix[i] = malloc(h * sizeof(BOOL)); 
    } 

    return newMatrix; 
} 
@end 
+0

Peut-être que vous devriez essayer d'exécuter avec malloc de garde lib. –

Répondre

1

Il doit y avoir une différence importante entre le code affiché et le code dans votre programme, parce que je copié et collé cela dans un programme et il s'est bien passé sans s'écraser.

Donc la réponse à votre question est la suivante: tout comme dans le code que vous avez posté.

1

Ce:

newMatrix = malloc(w * sizeof(BOOL *)); 

int i; 
for(i = 0; i < w; i++){ 
    newMatrix[i] = malloc(h * sizeof(BOOL)); 
} 

n'est pas un tableau à 2 dimensions. C'est un tableau de pointeurs sur tableau.

Un tableau 2 dimensions serait réparti comme:

newMatrix = malloc(w * h * sizeof(BOOL)); 

Voir http://en.wikipedia.org/wiki/C_syntax#Multidimensional_arrays

Questions connexes