Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Altering an array from a function in C++

Tags:

c++

arrays

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}.

like image 851
joker Avatar asked Nov 08 '12 18:11

joker


2 Answers

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); 
like image 129
GraphicsMuncher Avatar answered Oct 12 '22 14:10

GraphicsMuncher


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.

like image 35
kevintodisco Avatar answered Oct 12 '22 14:10

kevintodisco