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

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

Linda Hamilton
Release: 2024-12-11 03:03:12
Original
862 people have browsed it

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

Pointer Expressions: Navigating ptr , ptr, and *ptr

These pointer expressions are often encountered in C programming and can be tricky to understand. Here's a detailed explanation:

1. *ptr

  • Precedence: * (indirection) has higher precedence than (increment).
  • Expression Value: Evaluates to the value pointed to by ptr before incrementing.
  • Side Effect: Increments ptr by one memory unit.

Example:

int a = 5;
int *ptr = &a;

*ptr++; // evaluates to 5, then increments ptr to point to the next integer
Copy after login

2. * ptr

  • Precedence: (increment) and * (indirection) have equal precedence.
  • Expression Value: Evaluates to the value pointed to by ptr after incrementing.
  • Side Effect: Increments ptr by one memory unit.

Example:

int a = 5;
int *ptr = &a;

*++ptr; // evaluates to 6 (a++) and increments ptr
Copy after login

3. *ptr

  • Precedence: (increment) and * (indirection) have equal precedence.
  • Associativity: Right-to-left.
  • Expression Value: Increments the value pointed to by ptr.
  • Side Effect: None.

Example:

int a = 5;
int *ptr = &a;

++*ptr; // increments a to 6
Copy after login

4. (*ptr)

  • Precedence: Parentheses override precedence rules.
  • Expression Value: Evaluates to the dereferenced value at ptr before incrementing.
  • Side Effect: Increments the dereferenced value.

Example:

int a = 5;
int *ptr = &a;

(*ptr)++; // evaluates to 5, then increments *ptr to 6
Copy after login

Note that ptr , ptr, and ptr can crash if ptr is an array identifier, while (ptr) can crash if ptr points to a string literal.

The above is the detailed content of What's the Difference Between `*ptr `, `* ptr`, ` *ptr`, and `(*ptr) ` in 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