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
}
};
3 Answers 3
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)
{
}
};
1 Comment
count is not a compile time constant. But std::vector<Particle> would do fine.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.
Comments
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
}
};
Particle. See this.std::vector<Particle>instead of the dynamically allocated array.