Reputation: 139
I created a vector to store 96 computed values in it. The function is fine and returning the vector with size=96.
However when I call the vector in my draw-function its size is zero causing an access violation.
vector<float>Icosphere::calcIcosphere() {
//variables
vector<float> vertices (12*8)
//computing values
return vertices; //at this point the size=96
}
void Icosphere::drawIcosphere() const{
//variables
//create VAO
//generate buffer for VBO & IBO
vector<float> vertices; //here its size=0 and stays 0
//bind buffers and fill with vector and indices
....
glDrawElements(...); //causing access violation
...
}
I do not understand why the vector becomes 0 after returning its values. I guess I missed some basics.
Can somebody help?
Upvotes: 0
Views: 126
Reputation: 415
Those std::vector-s named 'vertices' in your functions are completely different instances so changing one does no affect the other. Your code probably should look like that:
void Icosphere::drawIcosphere() const{
//variables
//create VAO
//generate buffer for VBO & IBO
vector<float> vertices = calcIcosphere();
//bind buffers and fill with vector and indices
....
glDrawElements(...); //causing access violation
...
}
Upvotes: 0
Reputation: 238331
A local variable in one scope is a completely separate from a local variable in another scope, even if they share the same name. A simpler example:
void foo() {
int bar = 1;
}
void baz() {
int bar = 2;
}
These two bar
variables are different objects and have no releation between them. In fact, on every call to each function, a new local object is created. Furthermore, the objects don't even exist except for within the respective functions where they are declared.
When you declare a variable like this:
vector<float> vertices;
You default-initialise it, and it will be an empty vector. Whether there has been another vector variable prior to this or not has no effect on the contents of this vector.
Upvotes: 1