I'm having a newbie problem in C++.
I have a struct Edge defined as following:
struct Edge {
int position[4];
int average;
};
Now I need to create a lot of these structs and I created a helper-method for that, that creates an array of these structs based on some parameters:
Edge* createEdges(int some_parameters){
Edge *edges = new Edge[8];
for(int i = 0 ; i < 8; i++){
Edge edge;
edge.position[0] = 1; //fill the rest of the edge array in the same manner
edge.average = 10;
edges[i] = edge;
}
return edges;
}
However when I now call: Edge *edges = createEdges(int some_parameters) there is no sensible data in the Edge array (out of scope?).
I think I'm mixing up some things here but I would prefer if I can make this work without resorting to the vector datastructures. Is this the normal way of handling this or should I declare the edge array myself and pass it to the helper method to fill it up?
Edit:
First of all, I want to thank everyone for there comments/hints/tips/advice/... they have helped me to find the problem that I overlooked so easily.
After I seen the replies that the code should work, I tested the simplified code aswell (something I should have done in the 1st place) and surprisingly, it worked! So then I checked to see why my real code didn't work and the simplified version did.
My real code looked like this:
Edge* createEdges(int some_parameters){
Edge* edges = new Edge[8];
if(some_parameter != 0){
//create the edges as in my 1st snippet
return NULL; //doh, should return edges here !
} else {
return NULL;
}
}
The reason why I had not seen that I simply returned the wrong value (NULL) was because the debugger showed me some 0xf6f6f6 addressess with some negative values for edge.position (something I don't quite understand, it should've just show me 0x000000, perhaps I was just imagining things).
All in all, this was an important lesson in why to never code after 3am, nothing good will come of it!
edges[i] = edgeit copies the contents of the struct into the array.edgesis an array of structs, not of pointers.