Home > Backend Development > C++ > What's the Difference Between `ptr `, ` ptr`, and ` *ptr` in C/C ?

What's the Difference Between `ptr `, ` ptr`, and ` *ptr` in C/C ?

Linda Hamilton
Release: 2024-12-20 07:20:09
Original
274 people have browsed it

What's the Difference Between `ptr  `, `  ptr`, and `  *ptr` in C/C  ?

Pointer Expressions: ptr , ptr, and *ptr

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.

*ptr

This expression dereferences the pointer and then increments the pointer's address.

Example:

char *p = "Hello";
while (*p++) {
    printf("%c", *p);
}
Copy after login

This code prints "ello" instead of "Hello" because the pointer is being incremented after accessing the character, skipping the 'H' character.

* ptr

This expression increments the pointer's address and then dereferences the pointer.

Example:

char *p = "Hello";
printf("%c", *++p);
Copy after login

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'.

*ptr

This expression dereferences the pointer and then increments the value at the address.

Example:

char q[] = "Hello";
char *p = q;
printf("%c", ++*p);
Copy after login

This code prints "I" as the value at the address is directly incremented to 'I'.

(*ptr)

This expression is slightly different and forces a dereference before incrementing the value.

Example:

char q[] = "Hello";
char *p = q;
printf("%c", (*p)++);
Copy after login

This code prints "H" and then makes the next increment target 'I'.

Conclusion

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template