#include<stdio.h>
int main()
{
char *s[] = { "knowledge","is","power"};
char **p;
p = s;
printf("%s ", ++*p);
printf("%s ", *p++);
printf("%s ", ++*p);
return 0;
}
Output:
nowledge nowledge s
Please explain the output specially output from the 2nd printf() statement.I think that because ++ and * have same precedence therefore in *p++ p should be incremented first and then use *(associativity from right to left for unary operators).
According to C++ Operator Precedence:
“*” has the same precedence as prefix “++” but must be avaluated rigth to left.
printf(“%s “, ++*p);
So first
*pis evaluated, then++(*p), leading to the second character in the first string.“*” has less precedence than suffix “++”.
printf(“%s “, *p++);
So first
pis incremented, but it is a post-increment. The value returned from the operation is the original one. This way, the*operates over the original pointer, that pointed to the second char on the first string.Note that, this time,
++is operating overp, and not over*p.Since “2”,
ppoints to the second string. When you do++*pyou are now pointing to the second character of the second string (“s”). As you are again using a pre-increment, the value passed toprintfis already changed.printf(“%s “, ++*p);
I may get clearer if you do a little change and print the pointer value aswell (ignore the warnings):