question on complicated pointer/reference declarations

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Natasha26
    New Member
    • Mar 2008
    • 12

    question on complicated pointer/reference declarations

    I came across some strange declarations and am trying to get the hang of it. Any comments on how to read and use such decl. will be most welcomed.

    1) Not sure if i understand this one. It could be that function f can be used to increment the address of a pointer. So to use f(...) give it an argument of type: int*

    Code:
     void f(int*& i) { i++; }
    2) I got this one from pg35 of "C++ in a nutshell," i've put arrows to indicate where i got confused:
    Code:
    int x;           //some int
    int& r = &x;  //ref to int
    int* p = &x;  //pointer to int
    int*&* rp = &r;  //error: no pointer to ref  <---? 
    int*&* pr = p;   //ok: ref to pointer  <--- ?
    How do i read those in plain english and if i had a function f(int*&* p), or something more complicated, how do i know what type of argument it needs? thanks.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    It's quite simple: A reference is an alias for another variable. That is, it is a second name for the variable.

    You must bind the variable's name to the reference when the reference is created:
    [code=c]
    int a;
    int& b; //ERROR reference variable not identified
    int& c = &a; //ERROR a reference is not a pointer.
    int& c = a; //OK. c and a are the same variable.


    int* d = & a; //OK. d contains the address of a

    int*& e = d; //OK. e and d are the same variable.
    [/code]

    You see variable like e as function arguments. The argument becomes another name for the pointer in the calling function.

    You could use:
    [code=c]
    int** f = &d;
    [/code]

    Here you say that f contains the address of a pointer.

    In a function argument, a variable like f is used to change the value inside d. You can use e the same way except you don't need to dereference e like you do f.

    Comment

    Working...