GuybrushThreepwood
GuybrushThreepwood

Reputation: 5616

Setting Size of C-Struct Array Dynamically in Objective C?

In my OpenGL ES 2.0 project I have the following code in an object which initialises a Vertice and an Indice c-Struct array :

Vertex Vertices [] = {
{{0.0, 0.0, 0}, {0.9, 0.9, 0.9, 1}},
{{0.0 , 0.0 , 0}, {0.9, 0.9, 0.9, 1}},
{{0.0, 0.0, 0}, {0.9, 0.9, 0.9, 1}},
{{0.0, 0.0, 0}, {0.9, 0.9, 0.9, 1}},
};

static GLubyte Indices []= {
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
};

As I have different polygons that I want to render, I want to be able to set the Vertices and Indices dynamically from the calling class. I have tried just putting :

Vertex Vertices [] = {
};

static GLubyte Indices []= {
};

This is where I set the vertices to my verticeArray (this is the array which is set from the calling class).

- (void)setupMesh {
int count = 0;

for (VerticeObject * object in verticesArray) {

    Vertices[count].Position[0] = object.x;
    Vertices[count].Position[1] = object.y;
    Vertices[count].Position[2] = object.z;

    count ++;
    }
}

However this causes a crash, I assume because the array is never alloced / memory allocated. Can anyone suggest how I can achieve this ?

Upvotes: 0

Views: 730

Answers (1)

Peter Segerblom
Peter Segerblom

Reputation: 2813

You have to do something like this.

    int *arr = (int *)malloc(5*sizeof(int));

Where you can substitute int for your struct type, i.e..

typedef struct vertex {
  int x[3];
  float y[4]; 
} vertex;

int count = 10;

vertex *Vertices = (vertex *)malloc(count * sizeof(vertex));

you do need to release the memory when you are done.

free(Vertices);
Vertices = NULL;

Upvotes: 1

Related Questions