Home  >  Article  >  Backend Development  >  What is the difference between reference and pointer

What is the difference between reference and pointer

王林
王林Original
2020-07-18 15:43:4611402browse

The difference between a reference and a pointer is: 1. The program allocates a memory area for the pointer variable, but not for the reference; 2. The reference is initialized when it is defined and cannot be changed later, while the pointer can change; 3. Pointers need to be added with "*" when using them, and references can be used directly.

What is the difference between reference and pointer

First of all, pointers and references are concepts of address. A pointer points to a piece of memory, and its content is the address of the pointed memory; a reference is an alias for a certain piece of memory. .

(Recommended tutorial: c language tutorial)

Detailed introduction:

The program allocates a memory area for pointer variables, but not for references. .

When using pointers, add * in front, and references can be used directly.

The reference is initialized when it is defined and cannot be changed later; the pointer can change, that is, the referenced object cannot be changed, but the object of the pointer can be changed.

There is no null reference, but there is a null pointer. This makes code using references more efficient than using pointers. Because there is no need to test the validity of a reference before using it. In contrast, pointers should always be tested to prevent them from being null.

Using "sizeof" on the reference will get the size of the variable, and using "sizeof" on the pointer will get the size of the address of the variable.

Theoretically there is no limit to the number of pointer levels, but there is only one level of reference. That is, there is no reference to a reference, but there can be a pointer to a pointer.

int **p //合法
int &&p //非法

References and pointers have different effects.

For example, in terms of operations, the operation of the reference directly reflects the pointed object, rather than changing the pointer; and the operation of the pointer will make the pointer point to the next object, rather than changing the pointed object. content.

The above is the detailed content of What is the difference between reference and pointer. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn