Add element to pointer array
I have a pointer array of a custom Vector
typedef (just 3 floats). I'm writing a Wavefront object loader and I want to be able to add to an array of these vectors whenever a vertex row in the file is encountered. My problem at the moment is allocating memory for the new vector.
Vector
typedef struct
{
float x;
float y;
float z;
}
Vector;
Parsing the line and saving in memory
Vector *verticies;
Vector tmp;
verticies = new Vector;
long endPtr = sizeof(verticies);
sscanf(line, "v %f %f %f", &verticies[endPtr].x, &verticies[endPtr].y, &verticies[endPtr].z);
return;
There are eight vertices in the .obj
file and the output of sizeof(verticies)
shows 8 all the time. The problem with the code above is that the new vertex is given to the last element in *verticies
, so my question is; ** how do I add elements to the end of a pointer array dynamically?**
You are allocating space for exactly one Vector
struct.
sizeof(vertices)
will be the size of a pointer on your machine and is absolutely meaningless here.
sscanf(line, "v %f %f %f", &(verticies->x), &(verticies->y), &(verticies->z));
is going to do what you need. But this only enabling you to read in a single Vector
.
You either need to allocate enough space (as many vectors as you have lines) and use a for
loop to match the line with the offset in the array.
But you really should be using std::vector
and a std::ofstream
.
sizeof(verticies);
always gives 8, because it is a pointer, size of pointer on your environment is 8.
It does not mean you have 8 vertices.
If you want array of Vector of 8 items, you need to do:
Vector verticies[8];
If you do not know how many Vector
items you need to use at compile time you should use,
std::vctor
.
You should be using a std::vector
for this. (Or some other standard container.)
Nothing in your code contains an array of pointers. All you have is a pointer to a single Vector
item that you created with new Vector
.
sizeof(vertices)
will give you the size of vertices
which is a Vector*
. So sizeof(vertices)
will always return whatever the size of a pointer is on your platform.
Vector *verticies;
verticies = new Vector;
First of all, verticies
is not an array of pointers of type Vector
. It's just a pointer to Vector
. So, when ever you creating a instance, vecticies
is pointing to it. Leaving the last instance it was pointing to behind causing memory leak. If you need array of pointers, then it would be -
Vector *verticies[constant];
Since you tagged C++, std::vector
is apt for your program.
std::vector <Vector> verticies ;
Now, do a push_back operation for each instance you create.
精彩评论