What happened here? The C++ grammar effectively defines something we commonly refer to as "operator precedence" (since it's defined by the grammar, you won't find chapter in the C++ standard where the precedence would be listed in a convenient way, but there are websites that worked it out).
In *a++;
, the pointer will be increased (a++
) and thus pointing to an invalid position. After that, the invalid pointer will be dereferenced (*
operator), causing undefined behavior (UB). If you're learning, you want to get familiar with undefined behavior, because anything can happen.
To fix it, use parentheses to specify precedence explicity: (*a)++;
.
Maybe you want to learn about references instead? Don't use raw pointers and pointer arithmetic. Compare your code to this code:
#include<iostream>
using namespace std;
void increment(int& a){
a++;
}
int main(){
int a = 2;
increment(a);
cout << a;
return 0;
}
Also: Why is "using namespace std;" considered bad practice?