Daniela Diaz
Daniela Diaz

Reputation: 209

Equality between pointers in a function c++

Can you please tell me what's wrong when making equality between to pointers in a function. Let's see this example:

void fun(int *array1)
{
    int array2[5];
    for(int i=0;i<5;i++)
    {
        array2[i]=3;
    }
    array1=array2;
}


int main(){
    int x[5]; int n=5;
    for(int i=0;i<5;i++){
    x[i]=i; // --------> x[i]=i;
    }

    fun(x); //--------> x[i]=3

    for(int i=0;i<5;i++){
    cout<< x[i]<<" "; //-------> x[i]=i?????????? I expected x[i]=3;
    }

    return 0;
}

Upvotes: 0

Views: 99

Answers (2)

hetepeperfan
hetepeperfan

Reputation: 4411

You create a new array with the int[5] in your fun function I think you intend to do:

/**
  * not every array is 5 items long, thus it is unsafe
  */

void fun(int *array1)
{
    int* array2 = array1;
    for(int i=0;i<5;i++)
    {
        array2[i]=3;
    }
}

now int* array2 points to the array you call in the main function

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182763

void fun(int *array1)
{
    int array2[5];
    for(int i=0;i<5;i++)
    {
        array2[i]=3;
    }
    array1=array2; // **HERE**
}

When this function returns, array2 no longer exists. So even if this did return the value of array1 to the caller, the caller would just have a pointer to an array that no longer existed.

Of course, it doesn't even do that. array1=array2; sets the array1 variable to point to array2. But they're both local variables, so this has no effect on the caller anyway.

Perhaps you wanted:

 memcpy(array1, array2, sizeof(array2));

But this is C++, you should be using a sensible container like std::array.

Upvotes: 2

Related Questions