#c #arrays #exception #stack
#c #массивы #исключение #стек
Вопрос:
Когда я объявляю массив для хранения значений Y каждой координаты, определяю его значения, а затем использую каждое из значений элемента для отправки в функцию округления, я получаю сообщение об ошибке ‘Ошибка проверки во время выполнения # 2 — Стек вокруг переменной ‘Yarray; поврежден. Результат в основном соответствует ожидаемому, хотя мне интересно, почему это происходит, и если я могу это смягчить, приветствия.
void EquationElement::getPolynomial(int * values)
{
//Takes in coefficients to calculate Y values for a polynomial//
double size = 40;
double step = 1;
int Yarray[40];
int third = *values;
int second = *(values 1);
int first = *(values 2);
int constant = *(values 3);
double x, Yvalue;
for (int i = 0; i < size size 1; i) {
x = (i - (size));
x = x * step;
double Y = (third *(x*x*x)) (second *(x*x)) (first * (x))
Yvalue = Y / step;
Yarray[i] = int(round(Yvalue)); //<-MAIN ISSUE HERE?//
cout << Yarray[i] << endl;
}
}
double EquationElement::round(double number)
{
return number < 0.0 ? ceil(number - 0.5) : floor(number 0.5);
// if n<0 then ceil(n-0.5) else if >0 floor(n 0.5) ceil to round up floor to round down
}
Комментарии:
1. Почему у вас есть
size size 1
верхняя граница цикла? Этоi
соответствует 81, ноYarray
содержит только 40 элементов.2. Только что заметил ваш комментарий. Вот почему возникает ошибка.
Ответ №1:
// values could be null, you should check that
// if instead of int* values, you took std::vector<int>amp; values
// You know besides the values, the quantity of them
void EquationElement::getPolynomial(const int* values)
{
//Takes in coefficients to calculate Y values for a polynomial//
static const int size = 40; // No reason for size to be double
static const int step = 1; // No reason for step to be double
int Yarray[2*size 1]{}; // 40 will not do {} makes them initialized to zero with C 11 onwards
int third = values[0];
int second = values[1]; // avoid pointer arithmetic
int first = values[2]; // [] will work with std::vector and is clearer
int constant = values[3]; // Values should point at least to 4 numbers; responsability goes to caller
for (int i = 0; i < 2*size 1; i) {
double x = (i - (size)) * step; // x goes from -40 to 40
double Y = (third *(x*x*x)) (second *(x*x)) (first * (x)) constant;
// Seems unnatural that x^1 is values and x^3 is values 2, being constant at values 3
double Yvalue= Y / step; // as x and Yvalue will not be used outside the loop, no need to declare them there
Yarray[i] = int(round(Yvalue)); //<-MAIN ISSUE HERE?//
// Yep, big issue, i goes from 0 to size*2; you need size size 1 elements
cout << Yarray[i] << endl;
}
}
Вместо
void EquationElement::getPolynomial(const int* values)
Вы также можете объявить
void EquationElement::getPolynomial(const int (amp;values)[4])
Это означает, что теперь вам нужно вызвать его с указателем на 4 элемента; не больше и не меньше.
Кроме того, с std::vector
:
void EquationElement::getPolynomial(const std::vector<int>amp; values)
{
//Takes in coefficients to calculate Y values for a polynomial//
static const int size = 40; // No reason for size to be double
static const int step = 1; // No reason for step to be double
std::vector<int> Yarray;
Yarray.reserve(2*size 1); // This is just optimization. Yarran *Can* grow above this limit.
int third = values[0];
int second = values[1]; // avoid pointer arithmetic
int first = values[2]; // [] will work with std::vector and is clearer
int constant = values[3]; // Values should point at least to 4 numbers; responsability goes to caller
for (int i = 0; i < 2*size 1; i) {
double x = (i - (size)) * step; // x goes from -40 to 40
double Y = (third *(x*x*x)) (second *(x*x)) (first * (x)) constant;
// Seems unnatural that x^1 is values and x^3 is values 2, being constant at values 3
double Yvalue= Y / step; // as x and Yvalue will not be used outside the loop, no need to declare them there
Yarray.push_back(int(round(Yvalue)));
cout << Yarray.back() << endl;
}
}