对引用参数&的理解

#include<stdio.h>
#include<malloc.h>
struct node
{
    int s;
    struct node *l;
    struct node *r;
};
int sum=0;
int n;
void creat (struct node *&a,int key)    //改成struct node *a不对
{
    if(a==NULL)
    {
        a=(struct node *)malloc(sizeof(struct node));
        a->s=key;
        a->l=NULL;
        a->r=NULL;
    }
    else
    {
        if(key>=a->s)   //改成>不对
        {
            creat(a->l,key);
        }
        else if(key<a->s)
        {
            creat(a->r,key);
        }
    }
}
void zx()
{
    if(a==NULL)
    {
        return ;
    }
    zx(a->l);
    sum++;
    if(sum!=n)
    printf("%d ",a->s);
    else printf("%d\n",a->s);
    zx(a->r);


}
int main()
{
    while(~scanf("%d",&n))
    {
        sum=0;
        struct node *b;
        b=NULL;
        int i;
        for(i=1;i<=n;i++)
        {
            int k;
            scanf("%d",&k);
            creat(b,k);
        }
        zx(b);
    }
}




#include<stdio.h>
int a;
int main()
{
    int &p=a;
    a=2;
    printf("%d\n",p);


}

在c++中,&有两种含义,其中一种是取地址,另一种就是引用。 

引用是C++中的概念,初学者容易把引用和指针混淆一起。

一下程序中,n是m的一个引用(reference),m是被引用物(referent)。

int m;

int &n = m;

n相当于m的别名(绰号),对n的任何操作就是对m的操作。

所以n既不是m的拷贝,也不是指向m的指针,其实n就是m它自己。


在上面的程序的主函数中,b我并没有分配内存,而是让他为一个空指针,如果creat的参数我用struct node *a,这时a和b虽然都是NULL,但是都没有具体的指向地址,当在creat函数中给a分配内存时(即a有了新的地址指向),虽然之前a,b都是NULL,但此时的b的指向并没有更改,而用struct node *&a就不一样了,这里的a就是b的一个别名,creat函数中为a分配了内存也就是为b分配了内存。也就是当用struct node *时a和b是两个指针,用struct node *& 时,a和b是同一个指针。struct node *就像是两个人重名而struct node *就像是一个人大名和小名。

当事先为b分配好内存(即b指向一个具体的地址而不是NULL)时,struct node*和struct node *&对程序的影响几乎一样(但意义不同),否则struct node *和struct node *&是不一样的,以上程序就是后者。



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值