I have what looks to me an innocent cycle which iterates on elements of an array whose type is unknown at compile time; my array is named mesh->vertices and is a pointer to void. Depending on the truth value of mesh->textured I need to consider the array differently. Incidentally, the code in the if and the else in the code segment below is similar, but I do need to distinguish two cases.
void TransformMesh(struct Mesh *mesh, struct Matrix4 *t)
{
for (int i = 0; i < mesh->nVertices; ++i)
{
if (mesh->textured)
{
struct TexturedVertex *ptr = ((struct TexturedVertex *)mesh->vertices) + i;
ptr[i].position = MatrixPointMultiply3(t, &ptr->position);
ptr[i].normal = MatrixPointMultiply3(t, &ptr->normal);
}
else
{
struct Vertex *ptr = ((struct Vertex *)mesh->vertices) + i;
ptr[i].position = MatrixPointMultiply3(t, &ptr->position);
ptr[i].normal = MatrixPointMultiply3(t, &ptr->normal);
}
}
}
I guess I created the project with the Automatic Reference Counting option, thinking that it would not have affected C code, but now I feel like I'm wrong (by the way, how can I check which option I chose?).
Well, it looks like this function is doing something wrong with another array, called mesh->triangles, probably freeing it. When I try to use the vector I get an EXC_BAD_ACCESS error:
glDrawElements(GL_TRIANGLES, mesh->nTriangles * 3, GL_UNSIGNED_INT, mesh->triangles);
It looks like iterating on the mesh->vertices elements, casting them and doing the pointer arithmetic, is corrupting the memory. I think my problem is ARC, so I tried to do what described here but with no luck.
EDIT:
The code above was wrong, as pointed out by Conrad Shultz; the following is correct:
ptr->position = MatrixPointMultiply3(t, &ptr->position);
ptr->normal = MatrixPointMultiply3(t, &ptr->normal);