2

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);
8
  • 4
    Let me guess, because you use sizeof(vertices)? Note float * vertices; sizeof(vertices) return the size of the pointer and not the size of the array where the pointer refers to. Commented Oct 15, 2018 at 16:19
  • 1
    You have to post more code Commented Oct 15, 2018 at 16:47
  • @Jeka I have added more code to my original question. Hope this helps clarify what I'm actually doing. Commented Oct 15, 2018 at 17:32
  • @Noob "but it looks like my vertex buffer reads only the first element of the vertices array" - How do you specify the "vertex buffer"? Commented Oct 15, 2018 at 17:38
  • I've added how I specify the vertex buffer to my question. Commented Oct 15, 2018 at 17:46

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

Comments

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.