Chaos Project

General => Electronic and Computer Section => Programming / Scripting / Web => Topic started by: Apidcloud on November 16, 2012, 03:30:39 pm

Title: [C++] For each loop in order to allocate memory dynamically [Resolved]
Post by: Apidcloud on November 16, 2012, 03:30:39 pm
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();
Title: Re: [C++] For each loop in order to allocate memory dynamically
Post by: Blizzard on November 16, 2012, 03:57:09 pm
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)
Title: Re: [C++] For each loop in order to allocate memory dynamically
Post by: Apidcloud on November 16, 2012, 04:18:21 pm
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: