Crashed when transfer vertex without using buffer object

Hi dear all,
I’m new in OpenGL programming and trying the following code on Windows

struct data
  {
    float x,y,z,r,g,b;
  }
float vertices[] = 
  {
     0.5f,  0.5f,-5.0f,  1.0f,0.0f,0.0f,
     0.5f, -0.5f,-5.0f,  0.0f,1.0f,0.0f,
    -0.5f, -0.5f,-5.0f,  0.0f,0.0f,1.0f,
    -0.5f,  0.5f,-5.0f,  1.0f,1.0f,0.0f,
  };

glVertexPointer(3,GL_FLOAT,sizeof(data),(void*)vertices);
glColorPointer(3,GL_FLOAT,sizeof(data),(void*)(vertices+sizeof(data)/2));
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);

while(!glfwWindowShouldClose(window))
  {
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glDrawArrays(GL_LINE_STRIP, 0, 4);
    glfwSwapBuffers(window);
    glfwPollEvents();
  }

the executable crashed with access violation , what is missing ? many thanks!

In C, adding an integer to a pointer results in a pointer which is offset by the given number of elements (in this case, floats), not bytes. But sizeof(data)/2 is the desired offset in bytes.

So either cast vertices to a char*:

glColorPointer(3,GL_FLOAT,sizeof(data),(void*)((char*)vertices+sizeof(data)/2));

Or (arguably clearer):

glVertexPointer(3,GL_FLOAT,sizeof(data),(void*)&vertices[0].x);
glColorPointer(3,GL_FLOAT,sizeof(data),(void*)&vertices[0].r);
1 Like