2015-08-08 77 views
0

好了,所以我使用的是含有位置結構C風格的二維數組創建地圖:空調風格二維數組沒有保留價值

typedef struct{ 
    int x; 
    int y; 
} posn; 

我上傳的價值觀罰款並打印出來,以確保值是正確的。 2d數組作爲實例變量存儲在我的類中。

在我的下一個函數中,我首先打印數組以確保它是相同的,但事實並非如此。 值完全不同,數組甚至縮短。任何人都可以告訴我爲什麼我得到這個問題。我使用的是structs和c風格的數組,因爲我設計的是一個遊戲,我想他們會比NSMutableArray更快。

這是我的填充陣列

mapa_camino = (posn *)malloc(w * h * sizeof(posn)); 

int i, j = 0; 
for (i = 0; i < w; i++){ 
    for (j = 0; j < h; j++){ 
     SKNode *act; 
     act = [self.main_view nodeAtPoint:CGPointMake(i-algorimo_compensado.x, j-algorimo_compensado.y)]; 
     if([act isKindOfClass:[BasicActor class]] && ![act isKindOfClass:[CMActor class]]){ 
      //crea pt 
      posn pt = {.x = i, 
       .y = j, 
       .ocupado = YES, 
       .visitado = NO}; 
      //fija posicion actual como pt 
      *(mapa_camino + i*h + j) = pt; 
     }else{ 
      posn pt = {.x = i, 
       .y = j, 
       .ocupado = NO, 
       .visitado = NO}; 
      *(mapa_camino + i*h + j) = pt; 
     } 

    } 
} 

這是我的打印:

- (NSMutableArray*) printtwodarray:(posn*)matriz{ 
    int array_w = self.frame.size.width; 
    int array_h = self.frame.size.height; 
    NSMutableArray* regresa_matriz = [[NSMutableArray alloc] initWithCapacity:array_w]; 
    for(int i=0;i<array_w;i++){ 
     [regresa_matriz addObject:[[NSMutableArray alloc] initWithCapacity:array_h]]; 
     for(int j=0;j<array_h;j++){ 
      posn *pt = (matriz + i*array_h + j); 
      [[regresa_matriz objectAtIndex:i] insertObject:[[Posn alloc] initWithX:pt->x Y:pt->y H:pt->h G:pt->g Ocupado:pt->ocupado Goal:pt->is_goal] atIndex:j]; 
     } 
    } 
    return regresa_matriz; 
} 
+3

你可以發佈你如何填充數組,以及如何使用它進行打印? – Glorfindel

+1

你是否在你的函數中創建一個C數組,然後試圖將它作爲返回值傳遞出函數? –

+0

不,我將數組存儲爲一個實例變量,然後在我的後續函數中訪問它。 –

回答

0

爲了存儲從一個功能中的實例變量的2D陣列,並用它在另一個需要將變量聲明爲數組的函數,而不是指針。分配是行不通的,所以你需要用memcpy初始化數據:

@interface Foo : NSObject { 
    posn p[20][30]; 
} 
@end 
... 
-(void)bar { 
    posn d[20][30] = {{...}, {...},...,{...}}; 
    memcpy(p, d, sizeof(p)); 
}