-1

Having an array:

int a = { 1 ,2 , 3}

I can pass a pointer to a function in order to modify it.

int modify( int *a ){
   a[0] = 10;
}

But why can't I pass a reference to int to modify it? e.g

int modify( int &a ){
   a[0] = 10;
}

How does compiler manipulate with a reference? By using pointers, we pass the memory (in this case, the first element of the array ). But what happens with a reference? Why, for example, does this work?

vector<int > a 

void mod( vector<int> & a ){
      a[0] = 10;
     //a.push_back(10)
}
donjuedo
  • 2,475
  • 18
  • 28
Johnyb
  • 980
  • 1
  • 12
  • 27

1 Answers1

0

but why cant i pass reference to int to modify it?

You sure can.

The syntax needs to be a bit different for that.

int modify( int (&a)[3] ){
   a[0] = 10;
}

The difference between using

int modify( int *a ){ ... }

and

int modify( int (&a)[3] ){ ... }

is that you can call the first one using arrays of different sizes while the second one can be called only with arrays of size 3.

R Sahu
  • 204,454
  • 14
  • 159
  • 270