C++ 中的动态结构数组/无法从动态结构数组填充结构中的动态双精度数组

问题描述 投票:0回答:1

抱歉我的英语不好) 我创建了一个动态结构数组。该结构包含动态双精度数组。 当我添加结构时,我这样填充 边数和边长都平静地填好了,但是当涉及到顶点,或者更确切地说是一个顶点(沿着它我必须恢复其余的)时,输入任何数字后,程序就会崩溃

struct regular_polygon {
    int count_sides;
    double length;
    double square;
    double perimeter;
    double *x = new double[count_sides];
    double *y = new double[count_sides];
};



void SetData(regular_polygon* reg_pol, int amount, int* output)
{
    cout << "Enter count of sides:" << '\n';
    cin >> reg_pol[amount-1].count_sides;
    bool flag = false;
    if (reg_pol[amount].count_sides > 2) flag = true;
    while (flag == false)
    {
        cout << "Incorrect! Sides must be more than 2. Try again" << '\n';
        cin >> reg_pol[amount].count_sides;
        if (reg_pol[amount].count_sides > 2) flag = true;
    }


    cout << "Enter length of the side:" << '\n';
    cin >> reg_pol[amount].length;
    flag = false;
    if (reg_pol[amount].length > 0) flag = true;
    while (flag == false)
    {
        cout << "Incorrect! Length must be more than 0. Try again" << '\n';
        cin >> reg_pol[amount].count_sides;
        if (reg_pol[amount].length > 0) flag = true;
    }

    cout << "Enter vertex coordinates" << '\n';

    cout << "Enter x:" << '\n';
    cin >> reg_pol[amount - 1].x[ 0];   /// ТУТ ОШИБКА

    cout << "Enter y:" << endl;
    cin >> reg_pol[amount - 1].y[ 0];
    coordinates(reg_pol, amount);
}


    cout << "Enter vertex coordinates" << '\n';

    cout << "Enter x:" << '\n';
    cin >> reg_pol[amount - 1].x[ 0];   /// There is an error

我尝试将动态双精度数组替换为静态双精度数组,但不幸的是,它没有帮助

c++ function double structure dynamic-arrays
1个回答
0
投票

当您的对象初始化且

count_sides
有值时,您需要分配这些动态分配的数组。由于这是 C++,您可以为您的结构提供一个构造函数。

struct regular_polygon {
    int count_sides;
    double length;
    double square;
    double perimeter;
    double *x;
    double *y;

    regular_polygon(int count_sides, double length, double square, double perimeter)
    : count_sides(count_sides), 
      length(length),
      square(...),
      perimeter(...),
      x(new double[count_sides]),
      x(new double[count_sides])
    { }
};

现在您还需要担心析构函数和三/五/零的规则。

您可能想使用

std::vector
std::array

© www.soinside.com 2019 - 2024. All rights reserved.