Returning an pointer to an array safely?

So I have been trying to make a function that takes a sx, sy, and sz and then creates and returns an array of GLfloats that can be used by opengl.

1
2
3
4
5
6
7
8
  GLfloat* CPATriangleVerticies(float xs, float ys, float zs)
{
	GLfloat it[] = {
		-0.5f * xs, -0.5f * ys, 0.0f * zs,
		0.5f * xs, -0.5f * ys, 0.0f * zs,
		0.0f * xs, 0.5f * ys, 0.0f * zs };
	return it;
}

here it is!

Then I call it like so
1
2
3
4
5
6
7
GLfloat* v = CPATriangleVerticies(0.5, 0.5, 0.5);
	GLuint VBO;
	glGenBuffers(1, &VBO);
	//Tell it we are sending an array
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	//Tell it the data
	glBufferData(GL_ARRAY_BUFFER, sizeof(*v), v, GL_STATIC_DRAW);


Is this safe, or will the array not be passed properly. This question really has nothing to do with opengl I just need to know that it is safe to do stuff like this. Thanks!
Is this safe,

No. Returning a pointer to a statically allocated array is not allowed.
Last edited on
@jib

Is their a way I can do this and still have it be safe?
-Use vectors (return by value). http://www.cplusplus.com/reference/vector/vector/
You will then have to use &vec[0] to pass to glBufferData, lots of info online.

-Use std::array (return by value). http://www.cplusplus.com/reference/array/array/
Use data function to pass it to glBufferData.

-Pass an array by reference to CPATriangleVerticies and don't return anything.

You very rarely need to use C-style arrays if you are trying to stick with C++.
I vote for 1st or 2nd way.
CPATriangleVerticies() shouldn't allocate the array at all, it should just populate it. This is much more flexible since the caller can decide where the array is allocated:
1
2
3
4
5
6
7
8
void CPATriangleVerticies(float xs, float ys, float zs , GLfloat v[9])
{
    for (int i=0; i<9; i += 3) {
        v[i] = -0.f * xs;
        v[i+1] = -0.f * ys;
        v[i+2] = -0.f * zs;
    }
}


And the calling code:
1
2
3
4
5
6
7
8
GLfloat v[9];
CPATriangleVerticies(0.5, 0.5, 0.5, v);
GLuint VBO;
glGenBuffers(1, &VBO);
//Tell it we are sending an array
glBindBuffer(GL_ARRAY_BUFFER, VBO);
//Tell it the data
glBufferData(GL_ARRAY_BUFFER, sizeof(v), v, GL_STATIC_DRAW);

By the way, what is the 2nd parameter to glBufferData? I'm passing the number of bytes in the array. Is that right or should it be the number of items in the array?
Topic archived. No new replies allowed.