0

I'm trying to create an element/index array that I dynamically build with a set amount of memory. However, my code only works when I hard-code this array. In particular, the following is all the relevant code:

GLfloat elements[15 * 15 * 2 * 3 * 2];
GLuint second_elements[] = {
    0, 16, 17,
    0, 1, 17,
    1, 17, 18,
    1, 2, 18,
    ...
};
GLuint VBO;
glGenBuffers(1, &VBO);

GLuint EBO;
glGenBuffers(1, &EBO);

GLuint VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (void*)0);
glEnableVertexAttribArray(0);
...
glDrawElements(GL_TRIANGLES, sizeof(elements) / sizeof(elements[0]), GL_UNSIGNED_INT, 0);

When I use elements, my code doesn't render anything. When I use 'second_elements', my code renders everything perfectly. I've confirmed that they hold the same data, and have tried to just render one triangle from each as a test, but I just can't seem to get the EBO to load into VAO properly. Can anyone help?

  • Please provide a [mre]. The bug may be hidden in the code you did not post. Also, it is much easier and faster to help find a bug if a code that compiles and runs is available. – zkoza Apr 08 '22 at 01:01
  • Allocating lots of triangles on the stack is weird, as you risk a stack overflow. You should use dynamic memory, like `std::vector`, unless you have *very* good reasons not to. – zkoza Apr 08 '22 at 01:03
  • @zkoza Thanks for your input--I noticed that using std::vector works, but I didn't know why. I decided to go that route, but thanks for your input! – p0ptartlov3r Apr 08 '22 at 01:54
  • The reason for closing this question, link to "How do I determine the size of my array in C?", is dubious, but only because you did not provide a [mre]. The size of `elements` is only about 10 kB, the stack will certainly hold that much. The real problem is that you might use this style of coding elsewhere, and these 10 kB might be the last drop that makes the glass overflow. Pls always try to provide a [mre]. BTW, often, while preparing it, you'll find the solution yourself. – zkoza Apr 08 '22 at 12:10

1 Answers1

-1

Turns out, (for some reason) if I use a std::vector instead of normal heap memory, I can make this work by passing in elements.size() and &elements[0]. I don't know why, but I'll take what I can get.