0

I am newbie in c++ and just learning it. I have written the following code.

#include<iostream>
#include<cstdio>
using namespace std;
void first(int &x,int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        cout<<x+i;
    }
    cout<<endl;
}
void second(int *x,int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        cout<<*x+i;
    }
    cout<<endl;
}
int main()
{
    int exm[5]={1,2,3,4,5};
    first(exm[0],5);
    second(exm,5);

    return 0;
}

this program gives output correctly.but the problem is i don't understand the differences between using & and * in function parameters... both are the techniques of passing arguments by references and when we pass by reference we just send the memory address... but in function first when i tried to call the function as follows

first(exm,5);

function occurred an error. why ? but when i called the function as follows

first(exm[0],5);    

it compiled properly and gave right output...but i know that the both calling is equivalent... then why this error occured?
what is the difference between using & and * in function parameters?

MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
  • 1
    possible duplicate of [difference between a pointer and reference parameter?](http://stackoverflow.com/questions/620604/difference-between-a-pointer-and-reference-parameter) – Michael Petch Sep 26 '14 at 04:26

1 Answers1

1

The type of the variable exm is int[5], which doesn't meet the signature of first(int &x,int n).
But int[N] can be converted implicitly to int* that points to the first element of the array, hence second(exm,5) can compile.

what is the difference between using & and * in function parameters?

It's the difference between a reference and a pointer.

There are lots of differences between them.
In this case, I think the biggest difference is whether it accepts NULL or not.

See:
- What are the differences between a pointer variable and a reference variable in C++?
- Are there benefits of passing by pointer over passing by reference in C++?
- difference between a pointer and reference parameter?

Community
  • 1
  • 1
Ripple
  • 1,257
  • 1
  • 9
  • 15