0

I am trying to load a VAO in OpenGL, but when running it doesn't draw. When I use the code in my function directly into my main loop it runs fine but whenever I try to load the VAO via my function it doesn't work. I already narrowed it down to something going wrong when passing the values to the function, because when I directly use the float array it does work. I have the values defined as a static float array in my main function, and I'm loading it like this:

GLuint RenderLoader::load(float vertices[])
{
    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    GLuint vertexbuffer;
    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    return VertexArrayID;
}

1 Answer 1

5

The problem is with sizeof(vertices). Since the array is passed into a function, it then becomes a pointer, and sizeof returns the size of the first element pointer only. It is only known as an array in the scope where it was first initialised.

One solution would be to pass the size as an additional parameter, but really the only solution is to use some sort of container, like vector which has a size() function.

When using a vector, you would then do it in the following way:

GLsizei size = vertices.size() * sizeof(vertices[0]); // Size in bytes
glBufferData(GL_ARRAY_BUFFER, size, &vertices[0], GL_STATIC_DRAW);
Sign up to request clarification or add additional context in comments.

4 Comments

@robinvd95 If it works then accept the answer and upvote it.
sizeof(vertices) does not evaluate to the size of the first array element, but the size of the pointer.
It is a bit back to front. The function parameter is a pointer. It doesn't matter what gets passed to the function.
@derhass Thanks, fixed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.