为什么 ++(*ptr) 递增指针?

Why does ++(*ptr) increment the Pointer?

所以我是 C 的新手,用指针测试了一些东西,我对以下 printf 有疑问:

char txt[] = "thisIsAQuestion";
char *ptr = &txt[9];
printf("%c\n", ++(*ptr));
printf("%c\n", *ptr);

所以按照我的 "knowledge",它会是这样的:

指针指向值'e'。 然后,如果我执行第一个 printf,首先执行的是 () 中的命令,因此指针 *ptr 的取消引用,因为它比前缀增量具有更高的优先级。现在我认为 ++ 会像 (*ptr + 1) 那样工作,因为指针已经被取消引用,并且会增加指针指向的值,但不会更改指针本身。所以它将是 'f'。

但是现在当我 运行 第二个 printf 时,它告诉我指针仍然指向 'f' 而不是 "go back" 指向 'e'。

是不是我的想法有误?或者还有什么我没有考虑到的吗?

您遗漏了指针指向地址的部分,前缀 ++ 运算符更改了操作数的值。

++ will act like (*ptr + 1)

不,它的行为类似于*ptr = (*ptr + 1)

因此,(*ptr) 产生值 e,(正如预期的那样),然后通过应用 ++,该值递增并存储到同一内存中位置。

  • 前缀递增运算符的结果是新值,它作为参数传递给 printf() - 它打印该值。

  • 对于第二个 printf() 语句,您已经在打印增量值。

相关,引用C11,章节6.5.3.1

The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++E is equivalent to (E+=1).[...]

char *ptr = &txt[9]; 指向 txt 但从 e 字符开始。

printf("%c\n", ++(*ptr));语句首先增加e个字符并打印为f (e + 1 = f)

并且 printf("%c\n", *ptr); 语句只打印一个指向的字符(及其 f),因为 e 值随 ++(*ptr).

更改