2012-04-06 25 views
-1

(编辑:将在年底可能的解决方案)使用malloc创建我的类的2D空调风格阵列

我是C/C++程序员谁是学习Objective C的开发iPhone应用程序。我将要编写的程序将处理大型二维数组对象。我已经阅读了关于使用NSArray的NSArray,并且有一些工作代码,但我想了解如何使用C风格的数组来节省开销并学习你可以做什么和不可以做什么。

在这个片段中,MapClass只包含两个属性int x和int y。我有以下代码片段与一个静态定义的10x10数组一起工作。

MapClass *arr[10][10]; 

arr[2][3] = [[MapClass alloc] init]; 
arr[2][3].x = 2; 
arr[2][3].y = 3; 

NSLog(@"The location is %i %i", arr[2][3].x, arr[2][3].y); 
// Output: "The location is 2 3" 

这是一个维数组做和计算的例子,其中的细胞是基于X和Y:

MapClass **arr = (MapClass**) malloc(10 * 10 * sizeof(MapClass *)); 

arr[3 * 10 + 2] = [[MapClass alloc] init]; 
arr[3*10 + 2].x = 2; 
arr[3*10 + 2].y = 3; 

NSLog(@"The location is %i %i", arr[3*10 + 2].x, arr[3*10 + 2].y); 
// Output: "The location is 2 3" 

我的问题是:我怎样才能的malloc我的数组作为二维数组,以便我可以使用arr [2] [3]样式表示法来访问它?

我正在尝试的一切都会产生各种错误,如“下标需要您的类的大小,这在非易碎ABI中不是常量”。

任何人都可以给我如何做到这一点snippit?我一直在阅读和试验,无法弄清楚。我的一维数组示例是否有错误?

回答?

与xzgyb的答案混淆后,我有以下块工作。有什么问题吗?谢谢!

int dimX = 20; 
int dimY = 35; 

MapClass ***arr = (MapClass***) malloc(dimX * sizeof(MapClass **)); 
for (int x = 0; x < dimX; ++x) 
{ 
    arr[x] = (MapClass **) malloc(dimY * sizeof(MapClass*)); 

} 

for (int x = 0; x < dimX; ++x) 
{ 
    for (int y = 0; y < dimY; ++y) 
    { 
     arr[x][y] = [[MapClass alloc] init]; 
     arr[x][y].x = x; 
     arr[x][y].y = y; 

    } 
} 

for (int x = 0; x < dimX; ++x) 
{ 
    for (int y = 0; y < dimY; ++y) 
    { 
     NSLog(@"%i %i is %i %i", x, y, arr[x][y].x, arr[x][y].y); 

    } 
} 

// Cleanup 
for (int x = 0; x < dimX; ++x) { 
    for (int y = 0; y < dimY; ++y) { 
     [arr[x][y] release]; 
    } 
} 

for (int x = 0; x < dimX; ++x) 
{ 
    free(arr[x]); 
} 

free(arr); 
+0

这不是一个回答你的问题,但我想指出,你有没有用'malloc'在这里开始。 – 2012-04-06 03:37:24

+0

是的,片段是静态分配和工作。我想知道如何动态分配它与malloc。 – user1316642 2012-04-06 03:41:04

+0

哦,我明白了。感谢您的澄清! – 2012-04-06 04:27:12

回答

1

尝试被跟随代码:

MapClass ***arr = (MapClass***) malloc(10 * 10 * sizeof(MapClass *)); 

for (int row = 0; row < 10; ++row) { 
    arr[ row ] = (MapClass **)&arr[ row * 10 ]; 
} 

arr[0][1] = [[MapClass alloc] init]; 
arr[1][2] = [[MapClass alloc] init]; 
+0

这适用于我使用任何arr [0] [x],但只要尝试arr [1] [x]或更高,我就会碰到bad_access异常。我现在正在试验它,谢谢。 – user1316642 2012-04-06 05:11:07

+0

认为我有些工作,将其添加到第一篇文章。谢谢! – user1316642 2012-04-06 05:35:14

1

经过测试,它使用NSMutableString类和各种字符串方法工作正常。 我可能会推荐使用标准的消息发送方括号,而不是使用新的点运算符语法,以简化编译器实际要实现的功能。

如果我理解了你的意思,sizeof(ClassName )应该与sizeof([ClassName class])(和int或id)相同。你发布的代码不应该给出这样的错误,因为所有的指针都是相同的大小。现在,如果你尝试了sizeof(* someInstanceOfAClass)之类的东西,那么你遇到了一些问题,因为你试图malloc足够的内存来适应10 * 10 *(你的对象的实际大小),这不是你想要的去做。 (和听起来像你的警告适用于)