有那么一瞬间,懒得用NSArray,NSNumber,NSValue等一大堆蛋疼的转换,所以就定义了一个C的二维数组,反正OC支持C混编,可是蛋疼往往是传递的,这里不疼了,哪里就要疼,想把一个c的二维数组当成参数传递给另一个函数怎么办?各种尝试,最后想了一个办法,给大家分享下,不一定是最好的,大家有好的欢迎交流,废话不多说,上代码。
int dataArray[10][8] ={ {0, 0, 10, 0, 0, 0, 22, 0}, {0, 5, 10, 30, 0, 30, 21, 0}, {5, 20, 50, 40, 10, 50, 19, 0}, {5, 40, 60, 50, 20, 60, 17, 0}, {12, 60, 80, 60, 40, 80, 14, 0}, {20, 80, 80, 80, 80, 80, 12, 0}, {10, 60, 60, 60, 60, 60, 11, 0}, {10, 40, 40, 40, 30, 40, 10, 0}, {5, 20, 20, 20, 0, 20, 9, 0}, {0, 10, 10, 10, 0, 10, 8, 0} }; //不是不允许传么,nsdata总可以吧,反正本质都是二进制,转过去呗
NSData *data = [NSData dataWithBytes:dataArray length:sizeof(int) * 8 * 10]; //下面提供了两种转换回来的方式,为什么提供两种,自己体会吧,第二种记得使用完了Free()掉,不然………… int dataArray2[10][8]; [data getBytes:dataArray2 length:sizeof(int) * 8 * 10]; int * dataArray3 = malloc(sizeof(int) * 8 * 10); [data getBytes:dataArray3 length:sizeof(int) * 8 * 10]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 10; j++) { NSLog(@"%d", *(dataArray3 + 8 * i + j)); } }
free(dataArray3);
16年9月8日更新:
其实简单的是直接传递指针,数组的本质是一个连续的地址+一个指针,所以你可以这样
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. int dataArray[10][8] ={ {0, 0, 10, 0, 0, 0, 22, 0}, {0, 5, 10, 30, 0, 30, 21, 0}, {5, 20, 50, 40, 10, 50, 19, 0}, {5, 40, 60, 50, 20, 60, 17, 0}, {12, 60, 80, 60, 40, 80, 14, 0}, {20, 80, 80, 80, 80, 80, 12, 0}, {10, 60, 60, 60, 60, 60, 11, 0}, {10, 40, 40, 40, 30, 40, 10, 0}, {5, 20, 20, 20, 0, 20, 9, 0}, {0, 10, 10, 10, 0, 10, 8, 0} }; [self test:dataArray]; } - (void)test:(int *)data { for (int i = 0; i < 8; i++) { for (int j = 0; j < 10; j++) { NSLog(@"%d", *(data + 8 * i + j)); } } }