[C++] For each loop in order to allocate memory dynamically [Resolved]

Started by Apidcloud, November 16, 2012, 03:30:39 pm

Previous topic - Next topic

Apidcloud

Hey there dear fellows,
today my teacher asked to allocate memory dynamically (an array of pointers to a class), using new keyword

Of course that it can be done using a for loop but I thought about using a for each loop instead - that way I wouldn't need to know the array's size specifically.
Firstly, let's take a look to something I tried earlier:
int vec[3];
for each(int &v in vec)
v = 0;

I printed all vec's values and each one of them was initialized with 0  :)

As it worked just fine, I tried to apply the same thing, but this time to allocate memory dynamically:
#include "ClassX.h"
// [...]

ClassX *vecX[3];
for each(ClassX &v in vecX)
v = new ClassX();


It doesn't work, since we got a pointer's array, but I wasn't able to figure out how to do it properly either. I tried to use reference and desreference operators attached to vecX inside for each loop, but no luck at all. It keeps raising a syntax error when I change anything  :huh:

After a while, I started wondering if for each loop doesn't accept a pointer's array unless it is previously initialized(which I'm trying to do inside :^_^':)

Does anyone have a clue?

Thanks

Answer:
Code: by Blizzard
ClassX *vecX[3];
for each(ClassX* &v in vecX)
v = new ClassX();
Instead of wanting to be somebody else, rather become somebody else



"I will treasure the knowledge like a squirrel treasures acorns."


Gibbo Glast 2D Engine - The sky is no longer a limit

Blizzard

Eh, I have no idea where that each operator/keyword comes from, but it's not standard C++. But as far as I can see, it should be like this:

for each(ClassX* &v in vecX)


or this:

for each(ClassX &(*v) in vecX)
Check out Daygames and our games:

King of Booze 2      King of Booze: Never Ever
Drinking Game for Android      Never have I ever for Android
Drinking Game for iOS      Never have I ever for iOS


Quote from: winkioI do not speak to bricks, either as individuals or in wall form.

Quote from: Barney StinsonWhen I get sad, I stop being sad and be awesome instead. True story.

Apidcloud

Quote from: BlizzardEh, I have no idea where that each operator/keyword comes from, but it's not standard C++.

I got no idea either, just tried it once, and it worked  :roll:

The second option doesn't work - already tried it earlier.

The first one does  :haha: Thanks again Blizzard, I think I understand why it works  :haha:

Instead of wanting to be somebody else, rather become somebody else



"I will treasure the knowledge like a squirrel treasures acorns."


Gibbo Glast 2D Engine - The sky is no longer a limit