简体   繁体   中英

Pass by pointer/pass by reference in C

I know how to pass the pointer in function, I feel that I still confuse with two terminologies, such as pass by reference and pass by pointer.

I was asked this:

Write a program that uses pointers to pass a variable x by reference to a function where its value is doubled. The return type of the function should be void. The value of the variable should be printed from main() after the function call. The original value of x is 5.

I wrote the code below. can you tell me which comment number is right according to the question's demand and clear my doubt?

#include <stdio.h>
//double pointer
//void double_ptr(int **x_ptr)
//{
 //   **x_ptr *=2;

//}

void double_ptr(int *x_ptr)
{
    *x_ptr *=2;
}


int main()
{
    int x=5;
    int *x_ptr=&x;      // single pointer

    //double_ptr(*x_ptr);  // this is out of question's demand.
    //int**x_x_ptr=&x_ptr;    // double pointer
    //double_ptr(&x_ptr);     // 1. pass with double pointer
    //double_ptr(x_x_ptr);      //2. pass with double pointer
    //printf("%d",**x_x_ptr); //3.print with double pointer

    double_ptr(x_ptr);     //4.pass by pointer?
    //double_ptr(&x);          //5.pass by reference?
    printf("%d",*x_ptr);
    return 0;
}

Pass by pointer is actually pass by value, there is no such concept of passing by reference in C.

In C, pass by reference == pass by pointer.

void double_ptr(int *x_ptr)
{
      *x_ptr *=2;
}
int main()
{
      int x=5;
      double_ptr(&x); /* a value is being passed*/
}

Pass by reference (in C++):

void double_ptr(int& x_ptr)
{
   x_ptr *=2;
}
int main()
{
     int x=5;
     int &x_ptr=x;
     double_ptr(x_ptr); /* no temporary is being created i.e. no extra memory allocation is here*?
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM