As it stands right now, your code has undefined behavior, because it attempts to modify the contents of a string literal.
One way (probably the preferred way) to prevent the compiler from accepting such code is to define your a
like:
char const *a="asfsf";
This way, the ++*a
part simply won't compile.
For the sake of exposition, let's change the code a little bit, to become:
#include <iostream>
int main(){
char x[]="asfsf";
char *a = x;
++*a++;
std::cout<<x;
}
Now a
points at memory we can actually write to, and get meaningful results. This prints out bsfsf
. If we print out a
, we'll get sfsf
.
What's happening is that a++
increments a
, but still yields the original value of a
. That is dereferenced, giving a reference to the first element of x
. Then the pre-increment is applied to that, changing it from a
to b
.
If you want to increment the pointer, dereference the result, then increment that, you'd use: ++*++a;
. Well, no, you wouldn't use that--or at least I hope you wouldn't. It does increment a
to point at the second element of the array, then increment that second element to change it from s
to t
--but anybody who read the code would be completely forgiven if they hated you for writing it that way.