Reputation:
#include <iostream>
using namespace std;
void Fun(int arr1[], int arr2[])
{
arr1=arr2;
for(int i=0;i<5;i++)
{
cout<<arr1[i]<<" "<<arr2[i]<<endl;
}
}
int main() {
int arr1[5];
int arr2[5];
for(int i=0;i<5;i++)
{
arr1[i]=i+1;
arr2[i]=i;
}
Fun(arr1,arr2);
for(int i=0;i<5;i++)
{
cout<<arr1[i]<<" "<<arr2[i]<<endl;
}
return 0;
}
In the above code, why is arr1=arr2 in the Fun function, but on returning back from the function, arr1 has its initial values only?
Upvotes: 1
Views: 5524
Reputation: 75062
In function arguments, int arr1[]
has the same meaning as int *arr1
.
arr1=arr2;
is an assignment of pointers and now arr1
and arr2
point at (the head of) the same array, so the same array is printed in Fun()
.
On the other hand, the assigment affect only the pointer and not the arrays pointed at, so it will not affect main()
function.
To copy the contents of arrays, you can use std::copy
.
#include <iostream>
#include <algorithm> // for std::copy
void Fun(int arr1[], int arr2[])
{
std::copy(arr2, arr2 + 5, arr1);
for(int i=0;i<5;i++)
{
std::cout<<arr1[i]<<" "<<arr2[i]<<std::endl;
}
}
Upvotes: 2
Reputation: 60218
When you do:
arr1 = arr2;
you are simply assigning the address of the array arr2
to arr1
. So while this makes it appear as if the arrays are copied inside the function, this doesn't actually copy the contents of the arrays.
To do that you can use std::copy
like this:
std::copy(arr2, arr2 + 5, arr1);
Here's a demo.
Upvotes: 4