【问题标题】:why *s and *s++ have the same value in the following situation?为什么 *s 和 *s++ 在以下情况下具有相同的值?
【发布时间】:2016-04-07 22:04:37
【问题描述】:
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。但是为什么它们在这段代码中具有相同的值?

【问题讨论】:

  • “你的观点”是基于什么吗?
  • 后增量意味着执行然后增量。试试 *(++s)
  • s 表示字符串 s 的起始地址,所以 *s 应该是地址中存储的值。 s++ 应该是从字符串 s 的起始地址开始的下一个位置。
  • 也许你应该读一本 C 书?

标签: c pointers strchr


【解决方案1】:

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

  • 得到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

【讨论】:

    【解决方案2】:
    printf("%c\n",*s++);
    

    (或多或少1)等价于

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

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

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


    1。或多或少是因为s 将在评估*s 之后更新,但在实际调用printf 之前。没有指定具体何时应用 ++ 的副作用,只是它发生在下一个序列点之前。在这种情况下,在计算所有函数参数之后和调用函数之前会出现一个序列点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 2023-04-03
      • 1970-01-01
      • 2021-12-12
      • 2010-12-14
      • 2021-02-26
      相关资源
      最近更新 更多