-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++);

This code outputs:

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

In my view, *s should be t and *s++ should be e. But why they have same value in this code ?

Liyuan Liu
  • 105
  • 1
  • 1
  • 6

2 Answers2

5

In the expression *s++, ++ is the post-increment operator. That means following happens, in-order:

  • The value of s is gotten
  • Then s is incremented
  • Then the old value of s is de-referenced

So,

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

They will both print the same character.


If you want your example code to behave like you think it should, simply remove the first printf without the post-increment 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
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
1
printf("%c\n",*s++);

is (more or less1) equivalent to

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

This is why you see 't' printed twice.

The expression i++ evaluates to the current value of i, and as a side effect increments the variable.


1. More or less because s will be updated after *s is evaluated, but before printf is actually called. Exactly when the side effect of ++ is applied isn't specified, apart that it happen before the next sequence point. In this case, a sequence point occurs after all function arguments have been evaluated and before the function is called.
John Bode
  • 119,563
  • 19
  • 122
  • 198