Home >Backend Development >C++ >What's the Difference Between `ptr `, ` ptr`, and ` *ptr` in C/C ?
Understanding these three pointer expressions can be daunting. This detailed guide will break down each expression's operation and provide examples for their practical application in code.
This expression dereferences the pointer and then increments the pointer's address.
Example:
char *p = "Hello"; while (*p++) { printf("%c", *p); }
This code prints "ello" instead of "Hello" because the pointer is being incremented after accessing the character, skipping the 'H' character.
This expression increments the pointer's address and then dereferences the pointer.
Example:
char *p = "Hello"; printf("%c", *++p);
This code prints "e" as the character after the initial pointer value (which points to 'H') is accessed before being incremented to point to 'e'.
This expression dereferences the pointer and then increments the value at the address.
Example:
char q[] = "Hello"; char *p = q; printf("%c", ++*p);
This code prints "I" as the value at the address is directly incremented to 'I'.
This expression is slightly different and forces a dereference before incrementing the value.
Example:
char q[] = "Hello"; char *p = q; printf("%c", (*p)++);
This code prints "H" and then makes the next increment target 'I'.
These pointer expressions offer flexibility in pointer manipulation. However, it's crucial to be aware of their intricacies, including the order of precedence, value evaluation, and side effects. By understanding these operations in detail, you can effectively utilize them in your code and avoid potential pitfalls.
The above is the detailed content of What's the Difference Between `ptr `, ` ptr`, and ` *ptr` in C/C ?. For more information, please follow other related articles on the PHP Chinese website!