Altering an array from a function in C++
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);
I made a testcase.
http://ideone.com/fyl6MX
result
0 1 2
0x943b008
0x943b018
0x943b008
0 1 2
Second one is the address is a address of new table. As you can see your pointer is locally pointing to other address.
#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];
std::cout << x << endl;
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);
std::cout << y << endl;
someFunction4(y, 3) ;
std::cout << y << endl;
showArray(y, 3);
return 0;
}
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
.