您好我在iOS上编程和使用目标C相对较新。最近我遇到了一个我似乎无法解决的问题,我正在编写一个OBJ模型加载器,以便在我的iOS编程中使用。为此,我使用两个数组如下:
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 :(得分:1)
您可以使用c风格的malloc为数组动态分配空间。
int numOfVertices = //whatever this is read from file;
CGFloat *modelColours = (CGFloat *) malloc(sizeof(CGFloat) * numOfVertices);
答案 1 :(得分:0)
声明静态变量时,必须在编译时知道其大小和初始值。你可以做的是将变量声明为指针而不是数组,使用malloc
或calloc
为数组分配空间并将结果存储在变量中。
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,这样可以确保代码一致。