Reputation: 11
For some reason I cannot store data in an array if it is a pointer. If I stop it from being a pointer it works perfectly, but I need to have an array that holds a variable amount so it must be a pointer. Here is my code. Why is this array not storing more than one vertex at a time?
MVertex* Vertices = new MVertex[VertexCount];
//MVertex Vertices[4];
string LDum;
getline(Input, LDum);
for (int i = 0; i < 4; i++)
{
MVertex V;
string Line;
getline(Input, Line);
istringstream ISS(Line);
string X, Y, Z;
ISS >> X >> Y >> Z;
V.X = atoi(X.c_str());
V.Y = atoi(Y.c_str());
V.Z = atoi(Z.c_str());
Vertices[i] = V;
}
Input.close();
GraphicsDevice->CreateVertexBuffer(4 * sizeof(MVertex), 0, MFVF,
D3DPOOL_MANAGED, &MVertexBuffer, NULL);
VOID* pVoid;
MVertexBuffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, Vertices, sizeof(Vertices));
MVertexBuffer->Unlock();
int Size = sizeof(Vertices);
delete[] Vertices;
Upvotes: 0
Views: 63
Reputation: 39390
but I need to have an array that holds a variable amount so it must be a pointer
No, it doesn't have to be a pointer. Simply use std::vector<MVertex>
instead.
And your code doesn't work because of sizeof(Vertices)
, which will indeed give you whole array size for array types, but only the pointer size for pointer types.
That's another reason why pointer types used as arrays are particularly bad: there's essentially no way to get the size of the array; hacks similar to strlen
are extremely terrible non-solutions and C relicts.
Upvotes: 2
Reputation: 63481
Assuming that everything else has been set up correctly, this is most likely to be your problem:
memcpy(pVoid, Vertices, sizeof(Vertices))
That works on arrays because sizeof(Vertices)
returns the size of your array. But if Vertices
is a pointer, it will return the size of a pointer. You need to do 4 * sizeof(MVertex)
.
Upvotes: 0