This is one of the basic uses of pointers in C, let's take a look at a small example first. Here's the code:
int Main (void) { char'Hello'; while (*p++) printf ("%c", *p); return 0 ;}
The first sentence in this code is an expression:
Char " Hello ";
Declares a pointer to a char type P, what does it mean when we say "pointer to char type"? It's actually quite simple: the value of P is an address that holds a char type element, and P tells us that there is a variable of type char in memory.
This expression initializes the pointer p and points it to the first character of the string "Hello", for which we always remember that P is not the entire string, but just the first character "H", which means that the value of P is the address of "H" in the string "Hello".
Here is a loop:
while (*p++)
What does *p++ mean in this? General beginners will have the following several doubts:
- Priority of prefix + + and indirect value *.
- The case where the value of the suffix increment expression.
- The side-effects of the suffix increment expression.
1, priority , a quick look at the precedence table of the operator indicates that the precedence of the postfix operator (16) is higher than the reference operator (15). That is to say, *p++ can be expressed as * (p++), which means that * is acting on p++. First look at the p++ section.
2, suffix expression value , p++ value is the value of the p++ expression before p. Suppose you have:
int 7 ;p rintf ("%d\n", i++);p rintf ("%d\n", i);
The output will be:
7 8
You can see that the value of i++ is the value before I self-increment. So p++ is the value before P self-increment. The value in P is the address of "H".
The next *p++ is very simple, * represents the value of removing the current address in P, that is, "H".
Perhaps the reunion asked, since *p++ said "H", then why did not show it, the following will say side effects.
3, the side effect of the suffix expression , the value of the suffix + + expression is the value of the current variable, but there will be side effects after the expression operation. Look back at the above code and output.
The value of i++ in the first printf () function is 7, but in c it guarantees a moment before execution of the next statement (the reason is that the moment is related to the machine), and the side effects of this statement are generated, meaning that the value of the first I of the second printf () is bound to be added. Incidentally, this is one of the few side effects of the C standard that is guaranteed.
In the first code, when *p++ executes, he points to the character "H", but then the value of P adds one, and the final display on the screen is Ello.
Understanding *ptr++