-5

I was writing a code related to referencing in C/C++. I made a pointer and put it into a function that incremented it. In the function, I wrote *ptr++ and tried to increment the value of the integer the pointer was pointing at.

#include <iostream>
using namespace std;

void increment(int *ptr)
{
    int &ref = *ptr;
    *ptr++; // gets ignored?
    ref++;
}

int main()
{
    int a = 5;
    increment(&a);
    cout << a;

    return 0;
}

Can anyone please tell me why I can't increment the variable? I have tried incrementing it using +=1, and it works but not by using ++ operator?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 4
    [An image of your code is not helpful](https://idownvotedbecau.se/imageofcode) – Evg Oct 01 '20 at 05:36
  • 2
    Can you please tell me what's in that picture? Unfortunately I am blind, and my screen reader only spells out gibberish when it comes to that line. – πάντα ῥεῖ Oct 01 '20 at 05:37
  • 3
    Perfect dupe: [How to increment a pointer address and pointer's value?](https://stackoverflow.com/questions/8208021/how-to-increment-a-pointer-address-and-pointers-value) – Evg Oct 01 '20 at 05:40
  • 3
    [C++ operator precedence](https://en.cppreference.com/w/cpp/language/operator_precedence) – Remy Lebeau Oct 01 '20 at 06:35
  • 3
    Does this answer your question? [How to increment a pointer address and pointer's value?](https://stackoverflow.com/questions/8208021/how-to-increment-a-pointer-address-and-pointers-value) – Akib Azmain Turja Oct 02 '20 at 07:52

2 Answers2

6

++ has higher precedence than *, so *ptr++ is treated as *(ptr++). This increments the pointer, not the number that it points to.

To increment the number, use (*ptr)++.

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

Your code is:

*ptr++;

Which is equivalent to:

*(ptr++);

Which means pointer is incremented first and then dereferenced. this happens because increment operator ++ has higher precedence than dereferance operator * . So you should use:

(*ptr)++;

Here first pointer is dereferenced then incremented.

Akib Azmain Turja
  • 1,142
  • 7
  • 27