What is the difference between a pointer and a reference in C++

  • 2020-05-17 06:08:16
  • OfStack

What is the difference between a pointer and a reference in C++

1. In terms of memory, the system is a pointer sized memory space, and the reference shares the memory space with the bound object. The system does not allocate the content space for the reference variable.

2 pointer initialization can change the object pointed to, but the reference definition must be initialized, and after initialization is not allowed to re-bind the object.

3. So the reference access object is directly accessed. Pointer access object is indirect access.

4. If pa is a pointer, then *pa is referenced.

But the two are very similar when used as formal parameters, the difference being that the pointer copies the copy and the reference does not copy. The procedure is as follows:


#include<stdio.h>

void pt(int * pta,int * ptb)

{

int *ptc;

ptc=pta;pta=ptb;ptb=ptc;

}

void ref(int &ra,int &rb)

{

int rc;

rc=ra;ra=rb;rb=rc;

}

void main()

{

int a=3;int b=4;

int *pa=&a;int *pb=&b;

pt(pa,pb);

printf("zhizhen: a=%d,b=%d\n",a,b);

ref(a,b);

printf("yinyong: a=%d,b=%d\n",a,b);

}

The output results are as follows:


zhizhen: a=3,b=4

yinyong: a=4;b=3

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: