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
double *x = new double[count_sides]; double *y = new double[count_sides];You allocate arrays of an undetermined size, it results in undefined behavior. Doesn't the compiler warn you about that?std::vector<double>,double *x = new double[count_sides];is a valid but likely incorrect code.double *x = new double[count_sides]will cause magical resizing of the dynamically allocated array whenever the value ofcount_sideschanges. That is simply not the case. It accesses the current value ofcount_sidesand uses that value in thenewexpression - only at the time when an instance ofregular_polygonis created. If you want a "dynamic array" (one that grows when needed) then you MUST explicitly write code to explicitly resize it whenever needed.std::vectoretc.