Home > Backend Development > C++ > The difference between & and * in c++

The difference between & and * in c++

下次还敢
Release: 2024-04-26 17:55:44
Original
1126 people have browsed it

The difference between & and * in C is: & takes the variable address and stores the address in the pointer variable. Dereference a pointer variable to obtain the value it points to.

The difference between & and * in c++

The difference between & and * in C

Short answer:

& takes the variable address, while * dereferences the address.

Detailed explanation:

Get address (&):

  • & Operation operator is used to obtain the memory address of a variable.
  • Store the address in another variable, which is called a pointer variable.
  • The data type of the pointer variable must be the same as the data type of the variable pointed to.

For example:

int num = 10;
int *ptr = #
Copy after login

In the above code, ptr now points to the memory address of num.

Dereference address (*):

  • * The operator is used to dereference a pointer variable and obtain the value it points to.
  • It is equivalent to accessing the pointed variable.
  • You can use the * operator to read and write pointer variables.

For example:

int num = 10;
int *ptr = #
*ptr = 20;
Copy after login

In the above code, *ptr dereferences ptr and changes The value pointed to, that is, the value of num becomes 20.

Summary of differences:

Dereference Pointer variable, get the value pointed to
Operator Use
& Get variable address
##*
It should be noted that the

& and * operators are usually used in pairs. Use & to get the address, then use * to dereference the address to access or modify the value.

The above is the detailed content of The difference between & and * in c++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
c++
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template