I have written a program and in some part of my code it takes input from the console and according to that it creates pointers to objects and pushes them into a vector. Then it initializes the fields of these objects in the vector. It compiles. But when I try to run or debug it, I get an error message and the program crashes. And I really don't know why.
int main(){
string whatfix; // prefix infix or postfix
string exp; // expression like A-B+C
int varnum; // variable number
char var; // the variable, A,B,C etc.
int value; // the value of the variable
vector <VarObj*> varvect; // a vector in which we put the pointers of VarObj's, the variable objects, which stores the var character and its value
cin>>whatfix;
cin>>exp;
cin>>varnum;
for(int i=0 ; i<varnum ; i++){
cin>>var;
cin>>value;
VarObj *myvar; // a VarObj named myvar
varvect.push_back(myvar);
varvect[i]->var=var; // initializing the fields var and value of VarObj
varvect[i]->value=value;
}
.
.
.
}
When debugging .exe always stops launching at initializing the fields var and value of VarObj, at line 22 above. I don't get what the problem there is. Could you please help me?
Thank you.
Edit: It compiles no more. Says ".exe : permission denied". Dunno why.
Since your vector is a pointer to a custom class and you don't seem to assign any values to it outside of the loop I would guess that your for loop is over running the size of your vector array.
If you comment out the for loop and the initializing lines 22 and 23 what does varvect.max_size() return at this point in your code?
You're not creating any objects, just passing uninitialized pointers. You probably want to do this:
1 2
varvect.push_back(new VarObj); /* remember to delete these objects when destroying
the vector or you'll have a memory leak */
Remember that a pointer doesn't point to anything in particular unless you assign it some address. Since new allocates an object and returns a pointer to it, you can use it directly, as above, when you have a vector of pointers. Consider ownership carefully: the owner object must delete the objects pointed to by the vector (by calling delete on each of the pointers).
hmm... and then how should i delete all those objects in that vector? by for loop again? i don't know much about deleting and stuff. i tried to avoid using it, but it seems there's no other way to handle this.
edit: but actually i pass that varvect as a parameter to my further functions and use it in my code. should i still delete them, at least at the end of all the code?