在C中按指针传递/按引用传递 [英] Pass by pointer/pass by reference in C

查看:121
本文介绍了在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.

有人问我:

编写一个程序,该程序使用指针通过引用变量x来传递变量x 函数的值翻倍.函数的返回类型应该为空.这 函数调用后,应从main()打印变量的值.这 x的原始值为5.

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;
}

推荐答案

按指针传递实际上是按值传递,在C语言中没有这样的按引用传递概念.

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

在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*/
}

通过引用传递(在C ++中):

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*?
}

这篇关于在C中按指针传递/按引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆