alter array size in struct?

Discuss the development of new homebrew software, tools and libraries.

Moderators: cheriff, TyRaNiD

Post Reply
Ghoti
Posts: 288
Joined: Sat Dec 31, 2005 11:06 pm

alter array size in struct?

Post by Ghoti »

Hi folks,

Since i only know C and i do not know C++, i'm trying to make an .obj loader in c using a struct as some form of class. The problem however is that i do not know how to fill up an array of vertices inside a struct (change the number of the array), is it possible to initialize the array when you know the number of vertices you want to store?
memon
Posts: 63
Joined: Mon Oct 03, 2005 10:51 pm

Post by memon »

yes... if you use C++ it is really easy:

Code: Select all

#include <vector>

struct Vertex &#123; float x, y, z; &#125;

...

struct Mesh
&#123;
  std&#58;&#58;vector<Vertex> verts;    
&#125;;

...

Mesh* m = new Mesh;

int n = ReadNumVertices&#40;&#41;;
m->verts.resize&#40;n&#41;;

for&#40;int i = 0; i < n; ++i&#41;
  m->verts&#91;i&#93; = ReadVertex&#40;&#41;;
And If you need to pass the array to some function, which prefers a pointer to Vertex, it goes like this:

Code: Select all

void DrawVertexArrayThing&#40;const Vertex* verts, int n&#41;;
...
DrawVertexArrayThink&#40;&m->verts&#91;0&#93;, m->verts.size&#40;&#41;&#41;;
If you prefer C, you use malloc:

Code: Select all

struct Mesh
&#123;
  Vertex* verts;
  in nverts;
&#125;;

Mesh* m = new Mesh;

int n = ReadNumVertices&#40;&#41;;
m->verts = &#40;Vertex*&#41;malloc&#40;n * sizeof&#40;Vertex&#41;&#41;;
m->nverts = n;

for&#40;int i = 0; i < n; ++i&#41;
  m->verts&#91;i&#93; = ReadVertex&#40;&#41;;
The std::vector will free the memory for you when you destroy the mesh, but with the C method, you will need to free the mesh yourself:

C:

Code: Select all

free&#40;m->verts&#41;;
free&#40;m&#41;;
C++

Code: Select all

delete m
Ghoti
Posts: 288
Joined: Sat Dec 31, 2005 11:06 pm

Post by Ghoti »

Thanks that is really helpfull :) thanks again
Post Reply