Box2d - Variable length array of non-POD element type 'b2Vec2'

M0rph3v5 picture M0rph3v5 · Jul 26, 2011 · Viewed 8k times · Source

I'm working on a importer for a game of mine, it reads an xml and then creates the box2d bodies for everything.

For example

  <polygon vertexCount="3" density="0" friction="0.25" restitution="0.30000000000000004">
      <vertice x="6.506500000000001" y="0.4345"/>
      <vertice x="6.534970527648927" y="0.48385302734375"/>
      <vertice x="6.478029472351075" y="0.48385302734375"/>
  </polygon>

The problem is in the exporter I'm now facing the polygon part, I need to setup a b2vec2 array before adding the vertices and setting their positions.

int count = [[childnode attributeForName:@"vertexCount"] intValue];
b2Vec2 points[count];

but box2d wants the points[5] to be an actual literal number (like points[5] instead of a variable points[number], the error it outputs when I have the variable count in there is:

 Variable length array of non-POD element type 'b2Vec2'

How do I solve this? I tried making it a constant but that doesn't work either (and doesn't help me since I need it to be dynamic).

Answer

Andrew picture Andrew · Jul 26, 2011

You have to create the array on a heap:

b2Vec2 *array = new b2Vec2[count];

Don't forget to delete the array manually when finished.

or better use std::vector:

a)
std::vector<b2Vec2> vertices(count);
vertices[0].set(2, 3);
vertices[1].set(3, 4);
...

b)
std::vector<b2Vec2> vertices;
vertices.push_back(b2Vec2(2, 3));
vertices.push_back(b2Vec2(3, 4));