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
    }

};
3
  • what is your problem? Commented Mar 21, 2013 at 16:43
  • 1
    That's not a pointer to an array, that's an array of pointers to Particle. See this. Commented Mar 21, 2013 at 16:43
  • You could save yourself a lot of trouble by using an std::vector<Particle> instead of the dynamically allocated array. Commented Mar 21, 2013 at 16:52

3 Answers 3

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)
    {

    }
};
Sign up to request clarification or add additional context in comments.

1 Comment

@balki no, because count is not a compile time constant. But std::vector<Particle> would do fine.
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.

Comments

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
}

};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.