Search code examples
copenglopengl-3vertex-buffer

OpenGL vertices array initialisation


I have a question about OpenGL 3.0, why am I unable to draw anything when my array of vertices in initialized as

float * vertices;
int size = 100; // size of the vertices array
float * vertices = (float *) malloc (size*sizeof(float));

I have allocated memory, and initialized all the values in the array to 0.0, but it looks like my vertex buffer reads only the first element of the vertices array. Whereas when I initialize the array like this :

float vertices[size];

all the vertices are read and rendered as expected.

Here is how I specify my vertex buffer, and pass data to the buffer :

unsigned int VBO;
glGenBuffers(1, &VBO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);

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

GLint posAttrib = glGetAttribLocation(ourShader.ID, "aPos");

// iterpreting data from buffer 
glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 3* sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

Solution

  • sizeof doesn't do what you expect it to do. sizeof(x) returns the size of the data type of the variable x.

    In case of int size = 100; float vertices[size]; the data type of vertices is float[100] and sizeof(vertices) returns the same as sizeof(float)*100.

    In case of float * vertices;, the data type of vertices is float* and sizeof(vertices) returns the size of the pointer data type, which points to the dynamically allocated array, but it does not return the size of the dynamic memory or even the number of elements of the allocated array. The size of the pointer depends on the hardware and is the same as sizeof(void*) (usually it is 4 or 8).

    sizeof(float) * size would work in both of the cases of the question:

    glBufferData(GL_ARRAY_BUFFER, sizeof(float)*size, vertices, GL_STREAM_DRAW);