Home >Backend Development >C++ >Deeply understand the different functions of * and & in C language
The pointer () points to the variable memory address, and the address operator (&) obtains the variable address. Pointers are dereferenced using operators to access values, while address operators return a pointer to the location of a variable. These operators are used for dynamic memory allocation, linked list and array operations.
In-depth understanding of the different functions of * and & in C language
Pointer (*) and address operator (&) are There are two important operators in C language, but they have different functions.
Pointer (*)
A pointer is a variable that points to the address of a variable in memory. By using pointers, we can access the contents of this variable indirectly. Pointers are represented by an asterisk (*).
int x = 10; int *ptr = &x; // ptr指向变量x的地址
Now, ptr
points to the address of x
. We can use the *
operator to dereference the pointer and access the value of x
.
int value = *ptr; // value接收x的值
Address operator (&)
Address operator (&) gets the address of a variable. It returns a pointer to the memory location of the variable.
int x = 10; int *ptr = &x; // ptr接收x的地址
In this example, ptr
will contain the memory address of x
.
Practical case
Using pointers and address operators, we can implement many useful functions, such as:
To understand the difference between pointer and address operators, let’s see an example:
int x = 10; int *ptr = &x; int y = *ptr;
In this example:
ptr
is a pointer to x
, *ptr
is a dereferenced pointer, which contains the value of x
, which is 10. &x
is the address of x
, it is not a pointer, so we cannot dereference it. By understanding the difference between pointer and address operators, we can write more efficient and readable C code.
The above is the detailed content of Deeply understand the different functions of * and & in C language. For more information, please follow other related articles on the PHP Chinese website!