I
I
Igor Chuvilin2021-11-14 12:41:31
C++ / C#
Igor Chuvilin, 2021-11-14 12:41:31

Why does the value of a variable change after passing the value to a function (C++)?

I was looking for an answer, and I don’t understand why this can be so. Here is a quote from the source:

In the first example of this tutorial, we passed arguments by value to a function. This means that when a function is called, it is not the specified variables that are passed as actual parameters (arguments), but copies of the values ​​of these variables. The variables themselves have nothing to do with these copies. In the called function, these values ​​are assigned to parameter variables, which are known to be local. It follows that changing the passed values ​​does not have any effect on the variables passed to the function when called.

void input_array(int n, double *array) {
    //Ввод элементов массива
    for (int i = 0; i < n; i++) {
        cout << "(Ввод массива) M[" << i << "] : ";
        cin >> array[i];
    }
}
int main() {
    int count;
    int n;
    cout << "Введите колчество элементов. n : ";
    cin >> n;
    double array[n-1]; //Обьявление массива с заданным количеством n
    cout << endl << n << endl;
    input_array(n, array);
    cout << endl << n << endl;

    return 0;
}

Initially, we enter, for example 3
The first output gives, as it should be 3
The second one gives a random value.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2021-11-14
@dxmeqe

You are input_matrixout of bounds of the array: there are n-1 elements in the array, and you are reading n.
The array lies on the stack, in the same place as the local variable n. It so happened that n lies immediately after matrix (or within eight bytes) and is corrupted. The data seems random to you because you are reading a double and some part of it falls into the int n memory area.

R
Ronald McDonald, 2021-11-14
@Zoominger

You're creating a dynamic array incorrectly.
https://ravesli.com/urok-86-dinamicheskie-massivy/
And this is not a matrix, but a one-dimensional array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question