I’m trying to increment pointer. I was sure that it is similar to do i+=1
, but I’m getting adress.
#include \"stdafx.h\"
#include
If you want your output to be "43", than you have to change *a++;
to (*a)++;
.
But other than for testing and learning, code like yours is more of a "C thing" than a "C++ thing". C++ offers another approach to referencing data and operating on it, through what the language calls “references”.
int i=42;
int &a=i; // ‘a’ is a reference to ‘i’
a++;
assert(i==43); // Assertion will not fail
References are especially useful for passing arguments to functions, without the risk of having null or displaced pointers.
++
has a higher operator precedence than the pointer dereference operator *
.
So what *a++
does is to return the value of i
(the old value of *a
) before incrementing the pointer value.
After that expression has been evaluated, a
now points to something other than the address of i
, and the behaviour of a subsequent *a
is undefined.
If you want to increment i
via the pointer, then use (*a)++;
What does "I'm getting adress" mean?
Have you checked out order of operations?
http://en.cppreference.com/w/cpp/language/operator_precedence
++-postfix is a higher precedence than *-dereference - hence:
*a++;
is really:
*(a++);
and not:
(*a)++;
... as you probably meant. Which is IMHO why I always recommend erring on the side of too many parentheses rather than too few. Be explicit as to what you mean :)
Your code works fine till you reach the line
*a++;
As you know, C++ compiler will break this code of line as
*a = *(a+1);
That is, it will first increment address value of a and then assign the value to *a. But if you do,
*(a)++;
then you will get correct output, that is, 43.
For output- http://ideone.com/QFBjTZ
You have used *a++;
As your increment operator ++
has higher precedence than your pointer *
, what actually is happening is that your pointer address is being incremented. So the new *a has no defined value and hence it will give an undefined value
*a++;
is the equivalent of a++;
To fix this you can use parentheses (*a)++;
or simply us pre increment operator ++*a;