Sign in to follow this  
jkereluk

new keyword and arrays - can't figure it out

Recommended Posts

hey everyone, i cant figure this out! anyways the uncommented code works and shows my triangle the commented code doesn't. verticles is a vector of vertex objects with x, y, z
/*float * buffer = new float[(int)vertices.size() * 3]; // vert size * 3 = 9
for(unsigned int i = 0; i < (int)vertices.size(); i++)
{
    buffer[i * 3] = vertices[i].x;
    buffer[i * 3 + 1] = vertices[i].y;
    buffer[i * 3 + 2] = vertices[i].z;
}*/

float buffer[9];

buffer[0] = 0.0f;
buffer[1] = 1.0f;
buffer[2] = 0.0f;
buffer[3] = -1.0f;
buffer[4] = 0.0f;
buffer[5] = 0.0f;
buffer[6] = 1.0f;
buffer[7] = 0.0f;
buffer[8] = 0.0f;

glGenBuffersARB(1, &identifier);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, identifier);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(buffer), buffer, L_STATIC_DRAW_ARB);

Share this post


Link to post
Share on other sites
Don't use new[]. Use std::vector:

std::vector<float> buffer;
buffer.reserve(vertices_count * 3);

for (int i = 0; i < vertices_count; i++)
{
buffer.push_back(vertices[i].x);
buffer.push_back(vertices[i].y);
buffer.push_back(vertices[i].z);
}

glGenBuffersARB(1, &identifier);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, identifier);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, buffer.size() * sizeof(float), &buffer[0], L_STATIC_DRAW_ARB);


Share this post


Link to post
Share on other sites
sizeof(buffer) when buffer is a pointer to a dynamically allocated array is just going to give you the size of the actual pointer (i.e 4 bytes typically). You need to multiply it by the number of elements in the array.

Share this post


Link to post
Share on other sites
Quote:
Original post by Somnia
sizeof(buffer) when buffer is a pointer to a dynamically allocated array is just going to give you the size of the actual pointer (i.e 4 bytes typically). You need to multiply it by the number of elements in the array.


This was a bit carelessly expressed, of course I mean you need to multiply the size of a single element (e.g sizeof(float)) by the number of elements in the array.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this