The arrays are passed by reference. Any changes made to the array within the function changeArray
will be observed in the calling scope (main
function here).
However the codes below print 0 1
in the 1st cout
, and print 2
in the 2nd "cout". What I don't understand is that why the first cout
prints the original value of array[0]=1
instead of the changed value of array[0]=2
?
Thanks a lot.
#include <iostream>
using namespace std;
int changeArray(int array[]) {
array[0]=2*array[0];
return 0;
}
int main() {
int array[]={1,2,3,4};
cout << changeArray(array) << " " << array[0] << endl;
cout << array[0] << endl;
return 0;
}