0

I am using openGL and am currently passing it a vertex array. It is run successfully when I pass OpenGL a vertex array with an array like

    GLfloat vertices[] = {
    0.500000000f, 0.500000000f, 0.500000000f, 1.00000000f, 0.000000000f, 0.000000000f,
    0.500000000f, -0.500000000f, 0.500000000f, 1.00000000f, 0.000000000f, 0.000000000f,
    0.500000000f, 0.500000000f, -0.500000000f, 1.00000000f, 0.000000000f, 0.000000000f};

The problem is that when I passing it with a vector instead of the array like

    std::vector<GLfloat> vertices = {
    0.500000000f, 0.500000000f, 0.500000000f, 1.00000000f, 0.000000000f, 0.000000000f,
    0.500000000f, -0.500000000f, 0.500000000f, 1.00000000f, 0.000000000f, 0.000000000f,
    0.500000000f, 0.500000000f, -0.500000000f, 1.00000000f, 0.000000000f, 0.000000000f};

then I can't see the triangle in my window.

My code is almost like this https://learnopengl.com/code_viewer.php?code=getting-started/coordinate_systems_with_depth

And I changed this line

    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

into

    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices[0], GL_STATIC_DRAW);

And I changed these lines

    // Position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    // TexCoord attribute
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(2);

into

    // Position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    // NormalVector attribute
    glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(3);

because I need the normal vector information to do something else.

Does anyone know how to use std::vector correctly?

Thanks.

balthasar
  • 3
  • 1
  • 3

1 Answers1

3

If you are using a vector, you need to use vertices.size() * sizeof(GLfloat) instead of sizeof(vertices). The sizeof operator will give you the number of bytes of memory the vector occupies on the stack, not the size of the dynamically allocated array it contains.

Joseph Thomson
  • 9,888
  • 1
  • 34
  • 38