C 语言中的 ++*p、*p++ 和 *++p 的区别
指针算术
在 C 编程语言中,*p 表示存储在指针中的值。++ 是用于前缀和后缀表达式的自增运算符。* 是取值运算符。前缀 ++ 和 * 的优先级相同,并且都从右到左结合。后缀 ++ 的优先级高于前缀 ++ 和 *,并且从左到右结合。请看以下示例以了解 ++*p、*p++ 和 *++p 之间的区别。
示例 (C)
#include <stdio.h> int main() { int arr[] = {20, 30, 40}; int *p = arr; int q; //value of p (20) incremented by 1 //and returned q = ++*p; printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d
", arr[0], arr[1], *p, q); //value of p (20) is returned //pointer incremented by 1 q = *p++; printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d
", arr[0], arr[1], *p, q); //pointer incremented by 1 //value returned q = *++p; printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d
", arr[0], arr[1], *p, q); return 0; }
输出
arr[0] = 21, arr[1] = 30, *p = 21, q = 21 arr[0] = 21, arr[1] = 30, *p = 30, q = 21 arr[0] = 21, arr[1] = 30, *p = 40, q = 40
广告