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,584
  • 9
  • 47
  • 74

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
  • 55,379
  • 16
  • 141
  • 208
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
  • 108,238
  • 20
  • 242
  • 324
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,678
  • 8
  • 61
  • 92