为什么* s和* s ++在以下情况下具有相同的值?

时间:2016-04-07 22:04:37

标签: c pointers strchr

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。但为什么他们在这段代码中有相同的价值?

2 个答案:

答案 0 :(得分:5)

在表达式*s++中,++ 帖子 -increment operator 。这意味着跟随发生,按顺序:

  • 获得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而不在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

答案 1 :(得分:1)

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

(或多或少 1 )相当于

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

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

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

<小时/> 1。或多或少,因为s将在评估*s之后更新,但在实际调用printf之前。确切地说,除非是在下一个序列点之前发生,否则未指定++的副作用。在这种情况下,在评估所有函数参数之后和调用函数之前,会出现一个序列点