-5
char *s;
char buf [] = "This is a test";

s = strchr (buf, 't');

if (s != NULL)
    printf ("found a 't' at %s\n", s);
printf("%c\n",*s);
printf("%c\n",*s++);
printf("%c\n",*s++);
printf("%c\n",*s++);
printf("%c\n",*s++);

此代码输出:

found a 't' at test
t
t
e
s
t
Program ended with exit code: 0

在我看来,*s 应该是t,*s++ 应该是e. 但是为什么它们在这段代码中具有相同的价值?

4

2 回答 2

5

在表达式*s++中,++自增运算符。这意味着按顺序发生以下情况:

  • 的值得s
  • 然后s递增
  • s然后取消引用的旧值

所以,

printf("%c\n",*s);     // Prints the character at s
printf("%c\n",*s++);   // Prints the character at s
                       // ***and then*** increments it

他们都将打印相同的字符。


如果您希望您的示例代码表现得像您认为的那样,只需删除第一个printf没有后增量 on s

                        // s points to the 't' 

printf("%c\n",*s++);    // Prints 't'. Afterward, s points to the 'e'
printf("%c\n",*s++);    // Prints 'e'. Afterward, s points to the 's'
printf("%c\n",*s++);    // Prints 's'. Afterward, s points to the 't'
printf("%c\n",*s++);    // Prints 't'. Afterward, s points to the NUL terminator
于 2016-04-07T22:06:15.637 回答
1
printf("%c\n",*s++);

是(或多或少1)等价于

printf("%c\n",*s);
s++;

这就是为什么您看到't'打印两次的原因。

表达式i++计算为 的当前i,并作为副作用增加变量。


1. 或多或少,因为在评估s之后会更新,但实际调用之前。确切地说,没有指定应用的副作用,除了它发生在下一个序列点之前。在这种情况下,一个序列点出现在所有函数参数都被求值之后并且在函数被调用之前。*sprintf++

于 2016-04-07T22:15:37.743 回答