Kewal Shah
Kewal Shah

Reputation: 1260

Undefined Behaviour: value of array element changes implicitly/illogically

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 Output

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?

Upvotes: 0

Views: 102

Answers (1)

Ron
Ron

Reputation: 15501

You are reading out of bounds on numerous occasions thus invoking undefined behavior which may result in modified y[0] value. You defined the array bounds with:

double df[n - 1][n - 1];

but with the following statements and expressions you are accessing array elements out of bounds:

df[i][0] = y[i + 1] - y[i]; // everything except the y[i]
df[i + 1][j - 1]
df[i][j]
df[i][j - 1];
df[i + 1][j - 1]
df[i][0] = y[i + 1] - y[i]
df[i][j] = df[i + 1][j - 1] - df[i][j - 1]; // everything

Either modify the array bounds to be greater than n-1 or make sure the indexes are less than n-1 and n where appropriate to avoid undefined behavior. That being said, variable-length arrays are not part of the C++ standard.

Upvotes: 1

Related Questions