目标中的multidimensional arrayc
大家..
我想创build一个8 * 8维数组在目标c ..
( [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, 0], [0, 0, 0, 0, 0, 0, 0, 0], )
像那样..还可以用作其中的一个对象可以移动它..喜欢想移动
MOVE_ARRAY = array([0, 0], [0, 2])
也检查arrays的任何位置,如5 * 6或4 * 3任何..所以,任何人可以帮助我如何初始化,以及如何在代码中使用? 谢谢。
在Objective-C中:
array = [[NSMutableArray alloc] init]; for (int i = 0; i < 8; i++) { NSMutableArray *subArray = [[NSMutableArray alloc] init]; for (int j = 0; j < 8; j++) { [subArray addObject:[NSNumber numberWithInt:0]]; } [array addObject:subArray]; [subArray release]; }
( array
是一个实例variables,必须添加到你的头文件并在你的dealloc
方法中释放)
要在某个位置检索一个值,可以编写如下的方法:
- (int)valueAtRow:(int)row andColumn:(int)col { NSMutableArray *subArray = [array objectAtIndex:row]; return [[subArray objectAtIndex:col] intValue]; }
===更新===
要删除一个对象,你可以这样做:
- (void)removeObjectAtRow:(int)row andColumn:(int)col { NSMutableArray *subArray = [array objectAtIndex:row]; [subArray removeObjectAtIndex:col]; }
你必须小心,因为移除对象会改变数组的结构(例如,移除对象的行在移除后只有7个项目,所以你可能想要考虑保持结构完整并设置值你想删除一个你通常不用的值:
- (void)removeObjectAtRow:(int)row andColumn:(int)col { NSMutableArray *subArray = [array objectAtIndex:row]; [subArray replaceObjectAtIndex:col withObject:[NSNumber numberWithInt:-999]]; }
在C:
int **array = (int**)calloc(8, sizeof(int*)); for (int i=0; i<8; i++) array[i] = (int*)calloc(8, sizeof(int)); // use your array // cleaning: for (int i=0; i<8; i++) free(array[i]); free(array);
要创build一个包含整数的常量二维数组,只需执行如下操作:
NSArray *array; array = @[@[@1, @7, @4, @11],@[@2, @6, @9]];
这创build一个数组
1 7 4 11 2 6 9