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 ?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 03:52:13461browse

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

Pointers: ptr , ptr, and *ptr

These pointer expressions are often confusing, so let's clarify their meanings:

1. *ptr :

  • Dereferences the pointer ptr and returns the value pointed to.
  • Increments the pointer ptr to point to the next element.

Example:

int arr[] = {1, 2, 3};
int *ptr = arr;
cout << *ptr++; // Outputs 1 and then points to the next element (2)

2. * ptr:

  • Increments the pointer ptr first, moving it to the next element.
  • Then, дереференсирует the updated pointer, returning the value pointed to.

Example:

int arr[] = {1, 2, 3};
int *ptr = arr;
cout << *++ptr; // Moves the pointer to the next element and outputs 2

3. *ptr:

  • Dereferences the pointer ptr, returning the value pointed to.
  • Then, increments the dereferenced value.

Caution: Increments the value, not the pointer ptr.

Example:

int *ptr = new int(5); // Points to a dynamically allocated integer
cout << ++*ptr; // Outputs 6 and updates the dereferenced integer to 6

4. Bonus: (*ptr) :

  • Forces dereferencing of ptr, which obtains the pointed-to value.
  • Increments the dereferenced value.

Caution: Similar to *ptr, it affects the value, not the pointer itself.

Example:

int *ptr = new int(5);
cout << (*ptr)++; // Outputs 5 and updates the dereferenced integer to 6

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!

Statement:
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