Pointer, reference and parameter transfer

Source: Internet
Author: User
Today, when writing code for a double-stranded table, I encountered the following confusion: When function parameters are passed, the form parameter is declared

1 strunct queue *&Q;
Half a day * & QSo I read a lot of information about pointers and references, and finally solved the confusion.
First, let's briefly review PointerAnd ReferenceThese two operations.
1 int val; 2 int * Pv = & val; // pointer Declaration 3 Int & Rv = val; // reference Declaration

When initializing a reference type, it indicatesRvAndValIt can also be understoodRvYesValAlias,RvAndValA shared block of memory with the same address and value. While& ValMedium&It appears on the right side of the assignment number and becomes the right expression, which is a constant, indicatingValSo that we canInt * pv = & valTo declareInt *Pointer (pointing to int type)PvAssignedIntType VariableVal.

  1. When a pointer is passed as a function parameter, the address is passed.

    1 void swap(int *lhs,int *rhs){2     int *temp;3     *temp = *lhs;4     *lhs = *rhs;5     *rhs = *temp;6 }

    We

    1 int a,b;2 swap(&a,&b);

    In this caseLhs = & a; rhs = & B;EquivalentA,BThe address is passed as a function parameter.SwapOperation. The switch is within the address.A,BThe value of the variable, not the address exchange, so the exchange can be successful. If changed

    1 void swap(int *lhs,int *rhs){2     int *temp;3     temp = lhs;4     lhs = rhs;5     rhs = temp;6 }

    The exchange is not successful because the address is passed (Lhs (int *),Rhs (int *)) When the function returnsA,BAddress to restore the original value.

  2. When a reference is passed as a function parameter, the reference (alias) of the variable is passed. When a variable of the alias is changed, the variable of the original name also changes.
    1 void swap(int &lhs,int &rhs){2     int temp;3     temp = lhs;4     lhs = rhs;5     rhs = temp;6 }

    We

    1 int a,b;2 swap(a,b)

    Lhs,RhsYesA,B(Alias), we exchangeLhsAndRhsDirectly exchangedA,BThe valueLhsAndRhsUnchanged

  3. When the pointer is passed as a parameter, this will happen, that is, the variable we want to change through the function is a pointer, such
    1 int *pa = &a;2 int *pb = &b;

    We want to exchangePa,Pb(A,BIn this case, the pointer can be used for parameter transmission.

    1 void swap(int **lhs,int **rhs){2     int **temp;3     *temp = *lhs;4     *lhs = *rhs;5     *rhs = *temp;6 }

    We

    1 swap(&a,&b);

    When passing Parameters

    1 int ** lhs = & pa; // pa is int * type 2 int ** rhs = & pb; // pb is int * type

    ** LhsIt means the address variable pointing to the pointer.Lhs,& (Pa)Is forIntType pointer variablePaAddress, pointingInt *The pointer isInt **Type, so yes&Passed as a parameter eventually changedPa,PbIs changed.A,B.

  4. Finally, pointer reference is passed as a parameter.
    1 void swap(int &*lhs,int &*rhs){2     int *temp;3     *temp = *lhs;4     *lhs = *rhs;5     *rhs = *temp;6 }

    We

    1 int *pa = &a;2 int *pb = &b;3 swap(pa,pb);

    The value assignment expression when passing the parameter should be

    1 & * lhs = pa; // pa is int * type 2 & * rhs = pb; // pb is int * type

    Exchange* LhsAnd* RhsDirectly exchangedPa,PbValue, that is,* PaAnd* PbThe address does not change.Pa,PbThe value is&,& B, That isA,B.

Finally, let's look at this program.

 1 struct node 2 { 3        int data; 4        struct node *next; 5 }; 6   7 struct queue 8 { 9        struct node *head;10        struct node *tail;11 };12 void init(struct queue*& queue)13 {14      queue->head = queue->tail = new struct node;15      queue->head->next = NULL;16 }

Void init (struct queue * & queue );The*&Is to passQueue *Type pointer variable reference, then

1  main(int argc, char *argv[])2 {3     struct queue *Q;4     init(Q);5 }

When passing Parameters

Struct queue * & queue = Q; // reference queue-> head = queue-> tail = new struct node where Q is of the queue * type;

In factQ-> head,Q-> tailApplied for dynamic memory space,Q-> headAndQ-> tailAllStruct node *Type,Queue-> head-> nextMediumQueue-> headAndNextUsed as a connector->,Queue-> head-> next = NULL; ActuallyQ-> head-> nextThe value is a null pointer,Queue-> head-> nextDoes not point to any node. SinceQYesQueue *So we can use

1 void init(struct queue **queue);2 struct queue *Q;3 init(&Q)

In the formQueue *Type ParametersQThe answer is no. If the init function body is not modifiedQueueYesQueue **Type,-> HeadOnly AcceptQueue *Type, so the compilation fails. Summary:

  1. Two methods of changing the real parameter value during parameter transfer. a. the value in the address is changed during address transfer. (Pointer, pointer) B. Change the alias value during reference transfer (reference, Pointer Reference)
  2. Should I pass its pointer or reference when passing a parameter? This can be considered here, as shown inVoid func (int * & p),Func (?). It should be clear thatInt * & p =?The left and right types should match, so? It should beInt *TypeInt * & p = (int *). WhileVoid func (int ** p),Func (?)Medium,Int ** p =?Should it meet? YesInt *Type calculation, orInt ** p =?Yes? YesInt **Type (but it doesn't make much sense to pass such parameters), so? Yes& (Int *)Type,Int ** p = & (int *)Match between left and right.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.