Paul Reed
Paul Reed

Reputation: 113

Dynamically allocating length to an objective C static array

Hi I am relatively new to programming on iOS and using objective C. Recently I have come across an issue I cannot seem to solve, I am writing a OBJ model loader to use within my iOS programming. For this I use two arrays as below:

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

As can be seen the length is currently allocated with a hard coded value of 360 (the number of faces in a particular model). Is there no way this can be dynamically allocated from a value that has been calculated after reading the OBJ file as is done below?

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

I have tried using NSMutable arrays but found these difficult to use as when it comes to actually drawing the mesh gathered I need to use this code:

-(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);  
}

As you can see the command glVertexPointer requires the values as a CGFloat array:

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

Upvotes: 0

Views: 2242

Answers (2)

ughoavgfhw
ughoavgfhw

Reputation: 39905

When you declare a static variable, its size and initial value must be known at compile time. What you can do is declare the variable as a pointer instead of an array, the use malloc or calloc to allocate space for the array and store the result in your variable.

static CGFloat *modelColours = NULL;

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

I used calloc instead of malloc here because a static array would be filled with 0s by default, and this would ensure that the code was consistent.

Upvotes: 0

Chris McGrath
Chris McGrath

Reputation: 1936

You could use a c-style malloc to dynamically allocate space for the array.

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

Upvotes: 1

Related Questions