2011-09-25 49 views
0

嗨我相对较新的编程iOS和使用目标C.最近我遇到了一个问题,我似乎无法解决,我正在写一个OBJ模型加载器使用我的iOS编程。为此,我使用两个阵列如下:动态分配长度到一个客观的C静态数组

static CGFloat modelVertices[360*9]={}; 
static CGFloat modelColours[360*12]={}; 

如可以看到的长度当前与360°的硬编码值(面在特定模型的数量)分配。是否有没有办法可以从读取OBJ文件后计算出的值动态分配,如下所示?

int numOfVertices = //whatever this is read from file; 
static CGFloat modelColours[numOfVertices*12]={}; 

我一直在使用NSMutable阵列尝试,但发现这些困难,当涉及到实际绘制网格收集我需要使用这个代码使用方法:

-(void)render 
{ 
// load arrays into the engine 
glVertexPointer(vertexStride, GL_FLOAT, 0, vertexes); 
glEnableClientState(GL_VERTEX_ARRAY); 
glColorPointer(colorStride, GL_FLOAT, 0, colors); 
glEnableClientState(GL_COLOR_ARRAY); 

//render 
glDrawArrays(renderStyle, 0, vertexCount); 
} 

正如你所看到的命令glVertexPointer需要将值作为CGFloat数组:

glVertexPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); 

回答

0

当你声明一个静态变量时,它的大小和初始值必须在编译时已知。你可以做的是将变量声明为指针而不是数组,使用malloccalloc为数组分配空间并将结果存储在变量中。

static CGFloat *modelColours = NULL; 

int numOfVertices = //whatever this is read from file; 
if(modelColours == NULL) { 
    modelColours = (CGFloat *)calloc(sizeof(CGFloat),numOfVertices*12); 
} 

我用calloc代替malloc这里,因为静态数组会被默认以0填充,这将确保代码是一致的。

+2

再说一遍,不应该提到malloc或calloc给新手而没有提到需要在另一端免费。 –

+0

谢谢,这个工作使用calloc,现在我终于可以入睡了! @DanielRHicks关于释放记忆,好点,我会考虑明天尝试这样做! –

1

您可以使用c样式的malloc为数组动态分配空间。

int numOfVertices = //whatever this is read from file; 
CGFloat *modelColours = (CGFloat *) malloc(sizeof(CGFloat) * numOfVertices); 
+1

当然,如果有人这样做,他们需要确保在适当的时间释放阵列空间。 –

+0

谢谢,我也试过这个,这个工程也很棒。并占用较少的文本行! –