I want to know why does my code give a changed value of y[0] when I am nowhere changing it explicitly. I have provided the output in the link below:
Code:
#include <iostream>
int main() {
std::cout << "Enter total number of values of x/y" << std::endl;
int n;
std::cin >> n;
double x[n];
double y[n];
double df[n - 1][n - 1];
std::cout << "Enter values of x:" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> x[i];
}
std::cout << "Enter values of y:" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> y[i];
}
std::cout << std::endl;
for (int i = 0; i < n; i++) {
df[i][0] = y[i + 1] - y[i];
}
std::cout << "value of y[0] before: " << y[0] << std::endl;
for (int j = 1; j < n - 1; j++) {
for (int i = 0; i < n; i++) {
df[i][j] = df[i + 1][j - 1] - df[i][j - 1];
}
}
std::cout << "value of y[0] after: " << y[0] << std::endl;
}
Also, it gives an unchanged value of y[0] if I dynamically allocate memory using:
double* x = new double[n];
double* y = new double[n];
I referred to this link: Value of array member changes illogically, but I couldn't get a clear answer about how is it happening as it doesn't provide any code (as mentioned in the comments).
I want to know why is this happening in my code with static arrays and not dynamically allocated ones?