初始化指向数组的指针

Initialize pointer to array

本文关键字:指针 数组 初始化      更新时间:2023-10-16

我试图在类构造函数中初始化指向结构数组的指针,但它根本不起作用。。。

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 *parts;

使用C++,您可以使用std::vector:的优点

class Particles {
  // ...
 std::vector<Particle> parts;
 public:
    Particles (int count) : parts(count)
    {
    }
};
Particle * parts[];

这是一个指针数组。要初始化它,您需要遍历数组,初始化每个指针以指向动态分配的Particle对象。

您可能只想让parts成为一个指针:

Particle* parts;

new[]表达式返回一个指向数组的第一个元素(Particle*(的指针,因此初始化工作会很好。

试试这个:

类粒子{

私有:

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

公用:

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

};