-2

Please find my code-snippet below:

void inpu(vector<vector<int>> &pairs,int I){
 //Do something
}

int main() { 
    int I = 10;
    vector<vector<int> > pairs(N);
    inpu(pairs,I);
}

Now, I understand that the function inpu() expects an address of a vector type and an integer. My doubt is that when calling inpu(), why are we not passing an address of the vector pairs, as inpu(&pairs,I); in int main(), but as inpu(pairs,I);?

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
cazaimi
  • 196
  • 11
  • 9
    The `&pairs` **doesn't** mean that the function expects the address of a vector (that would be written as `* pairs`). It's a [pass-by-reference](https://www.tutorialspoint.com/cplusplus/cpp_function_call_by_reference.htm) argument, so it's called as shown. – lurker Mar 07 '17 at 11:50
  • &pairs is a pointer. That can be null. `inpu(... &pairs,...)` asks a reference. Not trivial to send in a null. See https://stackoverflow.com/questions/114180/pointer-vs-reference – wigy Mar 07 '17 at 11:52
  • `&` means very different things when used in a type and when applied to an expression as an operator. – molbdnilo Mar 07 '17 at 12:00
  • Misconception about what pointers? You aren't using any pointers in the code you show. – Algirdas Preidžius Mar 07 '17 at 12:05
  • @AlgirdasPreidžius I think that is the misconception, that a reference is a pointer. Or something like that. – luk32 Mar 07 '17 at 12:12

1 Answers1

1

Because you do not pass the object's address (a pointer). You pass the object itself (via a reference). Ampersand in the declaration of function argument is the syntax to distinguish that you want the object itself rather than a copy.

// This will copy the pairs
void inpu_c(vector<vector<int>> pairs){
}

// This will work on the original object
void inpu_r(vector<vector<int>> &pairs){
}

The pointer can be used as a reference type, you can dereference it and use the original object itself.

// This will work on the pointer
void inpu_p(vector<vector<int>>* pairs){
 pairs->clear();
 (*pairs).clear();

 // You can even use a reference type inside, you have to dereference a pointer
 assert(pairs); //Some protection against invalid pointers

 // a reference type requires an object
 vector<vector<int>>& r = *pairs;
 // will clear object pointer by pairs
 r.clear(); 
}

Using pass-by-value and pass-by-copy semantics do not change the client syntax though. The client code looks the same. That is why you don't have to use get-address operator (&) on the call site.

Pointers are slightly different from references, those two are different data types. E.g. pointer is nullable, i.e. has a special designated invalid value, while reference is designed to always point to an object.

luk32
  • 15,812
  • 38
  • 62