In your example code:
for(int i = 0; i < 2; i++){
MYSTRUCT *mystruct;
}
You're not creating objects at all. All you're doing is declaring pointers to MYSTRUCT. These pointers are uninitialized and therefore don't point to anything (yet). Moreover, the pointer (mystruct) itself is allocated on the stack and has a lifetime limited to the scope of your for-loop.
I am not sure what you are trying to achieve, but if you need multiple objects of type MYSTRUCT, you should not try to create them in a loop like that. Rather, declare an array or std::vector and initialize appropriately. I will leave it to you to figure out how to do this. When you do, be aware of the difference between static and dynamic arrays, and their consequences for memory management!
EDIT:
On request, I'll elaborate on the final snippet you provided:
vector<MYSTRUCT *> mystructs;
for(int i = 0; i < 100; i++){
MYSTRUCT *mystruct;
mystructs.push_back();
}
What happens here is you declare an empty vector of pointers to MYSTRUCT. So far so good. Now, judging on the body, you want to populate this vector with pointers to actual objects, but this is not happening in your code. I doubt this will even compile, given that push_back requires a MYSTRUCT* as an argument. Therefore, to do what you intend to do, your code should in each iteration:
- Allocate an object on the heap.
- Push a pointer to this object to the back of the vector.
This would look like the following:
vector<MYSTRUCT*> vec;
for (int i = 0; i != n; ++i) // pre-incr is good practice!
vec.push_back(new MYSTRUCT); // optionally add constructor arguments
However, this introduces you to new responsibilities: you are the one requesting the memory explicitly using new, so you should free the memory explicitly using delete. Unless MYSTRUCT is polymorphic (contains virtual members), you can easily circumvent this (even it it is polymorphic, you shouldn't do this, but that's another topic).
The answer to this problem is: don't store pointers, store objects:
vector<MYSTRUCT> vec; // no pointer!
for (int i = 0; i < 100; ++i)
vec.push_back(MYSTRUCT()); // create an unnamed instance and copy to the back of the vec
There, you have just created a vector of n MYSTRUCT instances. No pointers, no new and delete, simple and easy!