Home >Backend Development >C++ >Detailed explanation of the difference and usage of * and & in C language
In C language, it is used to dereference a pointer and return the value pointed to; & is used to take an address and return a pointer to the variable. Typically used to access or modify the value pointed to by a pointer; & is typically used to create a pointer or pass a reference.
Detailed explanation of the difference and usage of * and & in C language
In C language, *## There are important differences between the # and
& operators that work with pointers.
Operator*(Dereference)
Operator is used to dereference a pointer and return The value pointed to by the pointer.
, where
ptr is a pointer to a variable.
Example:
int *ptr; int value = 10; ptr = &value; // 为 ptr 分配 value 的地址 *ptr = 20; // 将 value 的值修改为 20
Operator&(get address)
The operator is used to take the address of a variable and return a pointer to the variable.
, where
var is a variable.
Example:
int value = 10; int *ptr = &value; // 为 ptr 分配 value 的地址
Difference
Dereference pointer,
& get variable address.
returns the value pointed to,
& returns a pointer to the value.
is typically used when creating a pointer variable or passing a reference as a function parameter.
is usually used when accessing or modifying the value pointed to by a pointer.
Practical case
The following is a practical case using the* and
& operators :
#include <stdio.h> int main() { int value = 10; int *ptr = &value; // 为 ptr 分配 value 的地址 // 使用 * 解引用指针并打印值 printf("Value: %d\n", *ptr); // 使用 * 修改指针所指向的值 *ptr = 20; // 再次使用 * 打印修改后的值 printf("Modified value: %d\n", *ptr); return 0; }
Output:
Value: 10 Modified value: 20
The above is the detailed content of Detailed explanation of the difference and usage of * and & in C language. For more information, please follow other related articles on the PHP Chinese website!