Passing Arrays to Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

void input (int test[5])
{
int i;
for(i=0;i<5;i++)
{
cout<<"Enter a number: ";
cin>>test[i];
}
}
int main()
{
int array[5];
input(array);
for(int i=0;i<5;i++)
{
cout<<array[i]; //shows the same values that i have input using the //function
cout<<endl;
}
return 0;
}


I am passing array to function but it is being passed by reference..Could you please explain this concept?
Why is this being passed as reference even though i am not using & operator to pass it as reference. I wrote a bubble sort algorithm using the same concept and i passed the array to function and did not return anything but it sorted the array in my main function which is weird as i did not pass the array by reference. I passed it like in the above program.
Could you guys please explain this?I've been trying to find answer on Google but haven't been able to find it yet.Hopefully you guys can help.
You see, array variable is a pointer, which points to memory area corresponding to first array element. So when you do that: input(array); You are passing pointer by value. Subscript operator ([]) dereference this pointer and you changing value pointer reference to.
1
2
3
4
5
6
7
8
9
10
void input (int test[5]); //equivalent functions
void input (int* test);   //You can freely interchange them and don't break anything

int array[5];
//Four following statements are equivalent
array[2];
*(array+2);
(array+2)[0];
(array+1)[1]
Topic archived. No new replies allowed.