I am new to C++ (the usual intro for every newbie XD) and I found this unexpected behavior. I traced the variables and arrays in my program until I determined this pattern:
#include <iostream>
using namespace std;
void showArray(int arr[], int n)
{
for(int i = 0; i < n; i++) cout << arr[i] << " ";
cout << endl;
}
void someFunction(int x[], int n) // changes the original values
{
x[0] = 2;
x[1] = 1;
x[2] = 0;
}
void someFunction2(int * x, int n)
{
x[0] = 2;
x[1] = 1;
x[2] = 0;
} // changes the original values
int someFunction3(int x[], int n)
{
x[0] = 2;
x[1] = 1;
x[2] = 0;
return 0;
} // changes the original values
int someFunction4(int x[], int n)
{
x = new int[n];
x[0] = 2;
x[1] = 1;
x[2] = 0;
return 0;
} // does NOT change the original value
int main(void)
{
int * y = new int[3];
y[0] = 0;
y[1] = 1;
y[2] = 2;
showArray(y, 3);
someFunction4(y, 3);
showArray(y, 3);
return 0;
}
Why doesn't someFunction4()
change the array y
in main()
? When I call the other someFunctionX()
in main()
instead, y
successfully changes from {0, 1, 2}
to {2, 1, 0}
.
In someFunction4
, you assign x
to point to a new
array of integers, which you then assign. The array pointed to by the variable you passed into the function still points to the old array. The old array stays unchanged, since within someFunction4
you've set x
to reference a different array, namely the one you created in your function via new
.
In order to make the original x
in someFunction4()
hold the values you assigned, do one of two things:
1) Get rid of x = new int[n];
. This will make someFunction4()
work like the previous ones.
2) Pass a pointer to x
as an argument to someFunction4()
and have someFunction4()
take a pointer.
int someFunction4(int *x[], int n)
{
*x = new int[n];
(*x)[0] = 2;
(*x)[1] = 1;
(*x)[2] = 0;
return 0;
} // Makes x point to a new a new array
And in your main, do
someFunction4(&y,3);
In each of someFunction
, someFunction2
, and someFunction3
, you are actually passing a pointer to the memory you allocated for your array in main()
. This means that when you operate on the data this pointer points to:
x[1] = 1;
It actually affects the same memory that y
points to back in main()
!
However, in someFunction4
, you reassign the pointer x
to point to new memory with the statement:
x = new int[n];
So it no longer points to the same memory that y
does in main()
, and any changes you make to it after that (but only within the scope of someFunction4
!) will not affect y
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With