指针和引用的区别
指针是一个持有某个变量内存地址的特殊变量,使用*
号表示。
引用类似于指针,一般可以认为是持有某个值的变量的别名,它被用来关联被赋值给它的变量,使用&
表示。
引用存储的是变量的地址。
语法层面的区别如下:
指针 | 引用 | |
---|---|---|
是否可以为null | 可以指向一个null | 不能为null,否则会报异常 |
声明方式 | 使用* 号声明 |
使用& 声明 |
是否可以级联 | 可以级联声明 int *ptr; int **ptr1; int x = 10; int y = 20; ptr = &x; ptr1 = &ptr; |
|
是否可以重新赋值 | 可以 | 一旦变量被赋值给引用变量,那么这个引用变量将不能重新被赋值 |
是否可以做算术运算 | 可以 | 不可以 |
S.No. | Pointer | Reference |
---|---|---|
1. | Pointers in C++ can be assigned to NULL values. | References in C++ can never be NULL else; it will throw an exception. |
2. | To dereference a variable in the case of pointers, (*) operator is used | There is no need for referencing the variable; the variable name is simply used in case of reference in C++. |
3. | Pointers allow multiple levels of indirection, which means that pointer to pointer to pointer assigning and targeting is possible. For example: int *ptr, int **ptr1; int x= 10; int y= 20; ptr = &x; ptr1 = &ptr; | No multiple levels of indirection are possible in the case of references. Only a single level is applicable in references. Implementing multiple levels in references in C++ throws a compiler error to the user. For example, int a = 13; int &ref = a; int &&ref1 = ref; |
4. | A pointer can be reassigned to point to another variable. But the variable needs to be of the same type of variable. For example: int *p; Int x, y; p = &x; p = &y; | Once the variable is referred to by the reference variable, it cannot be reassigned to refer to another variable. |
5. | All the arithmetic operations like addition, subtraction, increment, etc., are possible in the case of pointers in C++. This is known as Pointer arithmetic. For example: int arr [5] = {10, 20, 30, 40, 50}; int p = arr; for (int i =0; i<5; i++) { cout << *p << endl; p++; } | Arithmetic operations are not possible in the case of references. In C++, it will throw a compiler time error when it tries to do so. For example: int x = 10; int &ref = x; cout << ref++ << endl; |
6. | In the case of declaring a pointer in a C++ program, (*) operator is used before the pointer name. For example: int *ptr; | In the case of reference, the reference variable is declared by using the (&) operator before the reference variable, which stands for the address. For example: Int a= 10; int &ref = a; |
7. | The pointer variable returns the value whose address it is pointing to. Value can be retrieved using the (*) operator. | The reference variable returns the address of the address it is referring to. The address can be retrieved using the (&) operator. |
8. | The pointer variable in C++ has its own address in computer memory, and it also occupies space in the stack. | The reference variable does not have its own memory address; instead, it only points to the variable and shares the same address as the original variable. |