0

I am trying to initialize pointer to struct array in my class constructor but it do not working at all...

class Particles {

private:

    struct Particle {
        double x, y, z, vx, vy, vz;
    };

    Particle * parts[];

public:

    Particles (int count)
    {
        parts = new Particle [count]; // < here is problem
    }

};
Michal
  • 3,496
  • 7
  • 44
  • 70

3 Answers3

6

Remove those [] from declaration. It should be

Particle *parts;

Using C++, you can use benefits of std::vector:

class Particles {
  // ...

 std::vector<Particle> parts;

 public:

    Particles (int count) : parts(count)
    {

    }
};
masoud
  • 53,199
  • 16
  • 130
  • 198
2
Particle * parts[];

This is an array of pointers. To initialise this, you would need to loop through the array, initialising each of the pointers to point at a dynamically allocated Particle object.

You probably want to just make parts a pointer:

Particle* parts;

The new[] expression returns a pointer to the first element of the array - a Particle* - so the initialisation will work just fine.

Joseph Mansfield
  • 104,685
  • 19
  • 232
  • 315
1

Try this:

class Particles {

private:

struct Particle {
    double x, y, z, vx, vy, vz;
};

Particle * parts;

public:

Particles (int count)
{
    parts = new Particle [count]; // < here is problem
}

};

Leo Chapiro
  • 13,405
  • 7
  • 56
  • 87