Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
You are input_matrix
out 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.
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 questionAsk a Question
731 491 924 answers to any question