It is being called at the end of program, in the "delete" sequence, I guess. The program is working well all the way, except the end.
#include <iostream>
#include <cmath>
//Завдання 2, покажчикі
using namespace std;
int main()
{
int n = 10;
cout << "Input N (size of arrays): ";
cin >> n;
float* X = new float[n+1];
float* A = new float[n + 1];
float* max;
float* B = new float[n];
cout << "Input your X array (10 elems): " << endl;
//Логарифм від нуля завжди буде нескінченністю, отже, маємо рахувати з 1
for (int i = 1; i <= n; i++) {
cin >> X[i];
A[i] = cos(pow(X[i], 2)) + 4.5 * pow(log(pow(i, 2)), 2) + i;
}
max = new float( A[1]);
cout << "Your A array: " << endl;
for (int i = 1; i <= n;i++) {
if (A[i] > *max) max = &A[i];
cout << A[i] << " ";
}
cout << "\nYour B array: " << endl;
for (int i = 0; i < n; i++) {
B[i] = A[i + 1] / *max;
cout << B[i] << " ";
}
delete max;
delete[] X, A, B;
}
I tried to initialize max at the begining, giving it value of &A[0] (I know arrays are filled with random values when initialized, it doesn't matter). Then, I tried to initialize it in the first "for" loop like:
for (int i = 1; i <= n; i++) {
cin >> X[i];
A[i] = cos(pow(X[i], 2)) + 4.5 * pow(log(pow(i, 2)), 2) + i;
if (i == 1) max = &A[i];
else if (A[i] > *max) max = &A[i];
}
You have already being told in comment that your code does not follow best practices and will be hard to read and maintain. I had to read it many times to understand what it does...
The cause of the error is the
delete max;
instruction. You know that you must have adelete
pernew
, but you are expected to delete what have been allocate withnew
. And you change the value ofmax
(not*max
) in this code... So:I cannot understand why you have to use an allocated float instead of a simple variable, but as you already explained that you had to mix one and zero base indexing (which is a guarantee for later problems...), I will not go that way. But you must save the address of the allocated float and use it later to delete the object:
But IMHO this will only fix the current error, while you should considere rewriting to full piece of code in respect of best practices...