Home >Backend Development >C++ >Analysis and comparison of * and & operators in C language
In C language, the asterisk (*) operator is used to dereference a pointer variable and obtain the value of the variable pointed to; the address operator (&) is used to obtain the variable address. The specific comparison is as follows: Dereference pointer: *Get address: & pointer multiplication: *Bit operation: &
* and & operator analysis and comparison in C language
In C language, the asterisk (*) operator and the address operator (&) operator are two important operators, which are often used for pointer operations and memory management. This article will deeply analyze their uses and differences, and provide practical cases to illustrate.
The asterisk (*) operator
For example:
Address operator (&) operator
For example:
Comparison operator
The following is a comparison of the * and & operators in different scenarios:
Operator | Scenario | Function |
---|---|---|
* | Dereference pointer | Get the value pointed to the variable |
& | Get the address | Get the address of the variable |
* | Pointer multiplication | Calculate the size of the memory space pointed by the pointer |
& | Bitwise operation (logical AND) | Perform logical AND operation on two integers |
Practical Case
The following is a practical case that demonstrates how the * and & operators are used for pointer operations:
#include <stdio.h> int main() { int i = 10; int *ptr = &i; // ptr指向i // 通过解引用指针获取i的值 printf("i的值:%d\n", *ptr); // 通过取地址获取i的地址 printf("i的地址:%p\n", &i); // 通过指针乘法计算ptr指向的内存空间大小 int size = sizeof(*ptr); printf("ptr指向内存空间大小:%d字节\n", size); // 使用指针进行递增 (*ptr)++; // 打印递增后的i值 printf("递增后的i:%d\n", i); return 0; }
Output:
i的值:10 i的地址:0x7ffe5247ef4c ptr指向内存空间大小:4字节 递增后的i:11
The above is the detailed content of Analysis and comparison of * and & operators in C language. For more information, please follow other related articles on the PHP Chinese website!