Dynamic array of structures in C++/ cannot fill a dynamic array of doubles in structure from dynamic array of structures

43 views Asked by At

Sorry for my bad english) I created a dynamic array of structures. This structures contains dynamic array of doubles. When I add the structure, I fill it this way The number of sides and the length of the side are filled in calmly, but when it comes to the vertices, or rather to one vertex (along which I have to restore the rest), after entering any number, the program crashes

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

I tried to replace dynamic array of doubles to static array of doubles, but it didnot help, unfortunately

1

There are 1 answers

0
Chris On

You need to allocate those dynamically allocated arrays when your object is initialized and count_sides has a value. Since this is C++, you can give your struct a constructor.

Assuming square and perimeter are calculated from the number of sides and length of each side:

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

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

Now you also need to worry about a destructor and the rule of three/five/zero.

You also probably want to use std::vector or std::array rather than raw C-style arrays.