Home >Backend Development >C++ >Master the application scenarios and differences of * and & in C language
Pointers (*) store variable addresses and are used to access and modify variable values. The address operator (&) gets the address of a variable, which can be assigned to a pointer or passed to a function. The difference is: pointers can be dereferenced, while address operators themselves cannot access variable values.
Application scenarios and differences between pointers (*) and address operators (&) in C language
Pointers (*)
*
symbol, followed by the variable name Purpose:
Address operator (&)
&
symbol, preceded by the variable name Purpose:
Difference
Practical case
The following code example demonstrates the use of pointer and address operators in C language:
#include <stdio.h> int main() { int x = 10; // 获取 x 的地址并将其赋值给指针 p int *p = &x; // 使用解引用运算符 * 访问和修改 x 的值 *p += 5; // 打印修改后的 x 值 printf("x: %d\n", x); // 输出:15 // 传递 p 指针作为函数的参数 myFunction(p); return 0; } void myFunction(int *ptr) { // 修改指向值的变量 *ptr = 20; }
In this example Medium:
#*p
Dereference pointer p and access the pointed variable x. myFunction
receives a pointer to x p
and modifies the value of x through *ptr
. The above is the detailed content of Master the application scenarios and differences of * and & in C language. For more information, please follow other related articles on the PHP Chinese website!