I'm implementing a template pointer wrapper similar in functionaltiy to boost::shared_ptr.
I have a pointer to an integer ptrInt.
What I want to do: Increment the integer ptrInt points to.
My initial code was this: *ptrInt ++;, although I also tried the same using (*ptrInt) ++;
Apparently, however, this doesn't seem to do what I expected it to.
In the end I got it working using *ptrInt += 1;, however I'm asking myself:
What exactly does *ptrInt ++; do?
Is there a more elegant solution to using *ptrInt += 1;?
*p++ // Return value of object that p points to and then increment the pointer
(*p)++ // As above, but increment the object afterwards, not the pointer
*p += 1 // Add one to the object p points to
The final two both increment the object, so I'm not sure why you didn't think it worked. If the expression is used as a value, the final form will return the value after being incremented but the others return the value before.
x = (*p)++; // original value in x
(*p)++;
x = *p; // new value in X
or
x = ++*p; // increment object and store new value in x
*ptr++ equivalent to *(ptr++)
*ptrInt ++ will
increment ptrInt by 1
dereference old value of ptrInt
and (*ptrInt) ++ as well as *ptrInt += 1 will do what you want.
See Operator Precedence.
(*ptr)++ should do it, unless you are using its value right away. Use ++*ptr then, which is equivalent to ++(*ptr) due to right-to-left associativity.
On a side note, here is my smart pointer implementation, perhaps it can help you in writing your own.
The expression is evaluated using the rules for operator precedence.
The postfix version of ++ (the one where ++ comes after the variable) has a higher precedence than the * operator (indirection).
That is why *ptr++ is equivalent to *(ptr++).
You want (*ptrInt)++, which increments the object, which generally does the same as *ptrInt += 1. Maybe you have overloaded the += operator, but not the ++ operators (postfix and prefix increment operators)?
The more elegant way is whatever you tried before. i.e (*ptrInt) ++;
Since, you aren't satisfied with that, it might be because of the post - increment.
Say, std::cout<<(*ptrInt) ++; would have shown you the un-incremented value.
So, try giving ++(*ptrInt); which might behave as you expected.
*ptrInt++ in your case does increment the pointer, nothing more (before that it fetches the value from the location at throws it away. of course if you use it in a more complex expression it will use it)
(*ptrInt)++ does what you are looking for.
Related
I have a question about incrementing in pointers that I dont quite understand.
Lets see 2 small programs:
int iTuna=1;
int* pPointer= &iTuna;
*pPointer = *pPointer + 1 ; //Increment what pPointer is pointing to.
cout << iTuna << endl;
In this first program I increment what pPointer is pointing to like this "*pPointer = *pPointer +1".
And as I expected iTuna changed to "2" and the program printed out the value "2"
int iTuna=1;
int* pPointer= &iTuna;
*pPointer++; //Increment what pPointer is pointing to.
cout << iTuna << endl;
system("PAUSE");
return 0;
Here I incremented incremented what pPointer is pointing to this was "*pPointer++". But here iTuna stays as "1" and the programs prints out the value "1" .
Although I expected this one to work as the first, it didn't.
Please Help me and tell me why the second peice of code isn't working like I expected and how to get around it.
Thank You
*pPointer++;
is equivalent to
*pPointer;
pPointer++;
so it increments the pointer, not the dereferenced value.
You may see this from time to time in string copy implementations like
while(*source)
*target++ = *source++;
Since your problem is a matter of operator precedence, if you want to deref the pointer, and then increment, you can use parens:
(*pointer)++;
++ operator precedence is higher than *d dereference.
What you write is actually
*(p++)
However you should use
(*p)++
*ptr++; - increment pointer and dereference old pointer value
It's equivalent to:
*(ptr_p++) - increment pointer and dereference old pointer value
Here is how increment the value
(*ptr)++; - increment value
That's becuase ++ has greater precedence than *, but you can control the precedence using ()
In the Second program you are not increasing the the content at the pPointer address, but you are increasing the pointer. So suppose here if the pPointer value(memmory location allocated to iTuna) is 1000 then it will increase the location to 1000+2(int size)=1002 not the content to 1+1=2. And In the above program you are accessing the pointer location contents. Thats why you are not getting the expected results
*pPointer++; - Here dereference operator(*) has more precedence than increment operator(++). So this statement is first dereferencing and incrementing the pointer. After this you are printing the value of iTuna which will give you the same value. You are not printing the value by dereferencing pointer variable(*pPointer), because this will leads to crash(undefined behaviour). Because pPointer is now incremented.
Use like (*pPointer)++; to increment the value which is pointed by pPointer.
To get clear idea print the address stored in pPointer variable before and after your increment statement.
In the first case, the content of the pointer is incremented because *pPointer correspond to the content of the variable iTuna.
In the second one, the content is not incremented because you pPointer incrementing the pointer address. Remembering operator precedence rules, postfix operators such as increment (++) and decrement (--), have higher precedence than prefix operators, such as the dereference operator (*). Therefore, writting
*pPointer++
is equivalent to
*(pPointer++)
And what it does is to increase the value of pPoiner (so it now points to the next element), but because ++ is used as postfix, the whole expression is evaluated as the value pointed originally by the pointer (the address it pointed to before being incremented).
The correct code to have what you are expecting for is the following:
++*pPointer
or
(*pPointer)++
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 <iostream>
using namespace std;
int main()
{
int i = 42;
int *a = &i;
*a++;
cout << *a;
cin.get();
return 0;
}
Can anybody explain why ?
++ 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)++;
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.
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 :)
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;
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
I am trying to call a variable in my class using the this keyword in two ways but I am confused with the 2nd way. The correct way of dereferencing happens to be "(*this).num" however, I was wondering why "*(this).num" is not right as well. The error I get with *(this).num is
request for member 'num' in 'this', which is of pointer type çlass const'*
class::class(int n): num(n)
{
cout << "num= " << num << endl;
cout << "this->num" << this->num << endl;
cout << "(*this).num" << (*this).num << endl;
}
Because if you define
int i = 9;
int *ptr = &i;
cout<<*(ptr)<<endl;
and call *(ptr) it works. But why doesn't it work in my class?
It's simply a matter of operator precedence. The binary dot operator has a higher precedence than the unary star operator, so *(this).num (the parentheses have no effect there) is interpreted as *(this.num), and not as (*this).num. The compiler is telling you that, because this is a pointer, this.num doesn't make sense: you can't apply the dot operator directly to a pointer.
You are using two operators: the indirection/dereferincing operator * and the member access operator ..
If you have a look at the precedence of these operators, you'll see that . has higher precedence than * (that is, . will be applied before *), so thus *(this).num is basically the same as writing *(this.num).
Since this is a pointer, you can't use the . operator on it, which is also what the error message is telling you (try using -> instead).
The reason why your second example works, is that you're not using the . operator, and thus there is no precedence to be messed up.
. has higher precedence than *.
So writing *(this).num is equivalent to (*((this).num))). Or *(this.num).
Your second example is completely different from the first since there is no access to members . or ->.
If you don't know all the precedences, or even if you do, it's usually more readable to add the appropriate brackets.
One works and the other doesn't because they are not the same thing!
*(ptr) and *(this) are the same, but *(this).num and (*this).num are not the same, that's the whole point of adding the parentheses! They change how the sub-expressions are grouped, just like in mathematics.
The parentheses in (ptr) and (this) are completely redundant, you are grouping a single sub-expression, which does nothing. In (*this) it's not redundant, it ensures that you dereference the pointer, so in (*this).num it dereferences the pointer first and then the member access .num is applied to the result of that dereference.
Compare it to mathematics:
(1) is just 1, and similarly (ptr) is just ptr
-(1) is just -1, and similarly *(ptr) is just *ptr
But -(1 + 3) and -(1) + 3 are completely different, because you change the order of the operators.
Similarly, *(this.num) and (*this).num are completely different.
The short answer is syntax.
(ptr) looks like this: evaluate expr inside () first, then dereference the result which is in this case is int. It's fine, the same as *ptr.
*(this).num is eq. with *this.num which means get the num member of this. After that dereference num. It's incorrect as you can see because "this" is a pointer to the current object.
(*this).num means dereference this, then get the num member.
I have a question about incrementing in pointers that I dont quite understand.
Lets see 2 small programs:
int iTuna=1;
int* pPointer= &iTuna;
*pPointer = *pPointer + 1 ; //Increment what pPointer is pointing to.
cout << iTuna << endl;
In this first program I increment what pPointer is pointing to like this "*pPointer = *pPointer +1".
And as I expected iTuna changed to "2" and the program printed out the value "2"
int iTuna=1;
int* pPointer= &iTuna;
*pPointer++; //Increment what pPointer is pointing to.
cout << iTuna << endl;
system("PAUSE");
return 0;
Here I incremented incremented what pPointer is pointing to this was "*pPointer++". But here iTuna stays as "1" and the programs prints out the value "1" .
Although I expected this one to work as the first, it didn't.
Please Help me and tell me why the second peice of code isn't working like I expected and how to get around it.
Thank You
*pPointer++;
is equivalent to
*pPointer;
pPointer++;
so it increments the pointer, not the dereferenced value.
You may see this from time to time in string copy implementations like
while(*source)
*target++ = *source++;
Since your problem is a matter of operator precedence, if you want to deref the pointer, and then increment, you can use parens:
(*pointer)++;
++ operator precedence is higher than *d dereference.
What you write is actually
*(p++)
However you should use
(*p)++
*ptr++; - increment pointer and dereference old pointer value
It's equivalent to:
*(ptr_p++) - increment pointer and dereference old pointer value
Here is how increment the value
(*ptr)++; - increment value
That's becuase ++ has greater precedence than *, but you can control the precedence using ()
In the Second program you are not increasing the the content at the pPointer address, but you are increasing the pointer. So suppose here if the pPointer value(memmory location allocated to iTuna) is 1000 then it will increase the location to 1000+2(int size)=1002 not the content to 1+1=2. And In the above program you are accessing the pointer location contents. Thats why you are not getting the expected results
*pPointer++; - Here dereference operator(*) has more precedence than increment operator(++). So this statement is first dereferencing and incrementing the pointer. After this you are printing the value of iTuna which will give you the same value. You are not printing the value by dereferencing pointer variable(*pPointer), because this will leads to crash(undefined behaviour). Because pPointer is now incremented.
Use like (*pPointer)++; to increment the value which is pointed by pPointer.
To get clear idea print the address stored in pPointer variable before and after your increment statement.
In the first case, the content of the pointer is incremented because *pPointer correspond to the content of the variable iTuna.
In the second one, the content is not incremented because you pPointer incrementing the pointer address. Remembering operator precedence rules, postfix operators such as increment (++) and decrement (--), have higher precedence than prefix operators, such as the dereference operator (*). Therefore, writting
*pPointer++
is equivalent to
*(pPointer++)
And what it does is to increase the value of pPoiner (so it now points to the next element), but because ++ is used as postfix, the whole expression is evaluated as the value pointed originally by the pointer (the address it pointed to before being incremented).
The correct code to have what you are expecting for is the following:
++*pPointer
or
(*pPointer)++
If I have code like:
int pop()
{
return stack[--stp];
}
I know that it is doing two things. It is returning the value contained in the one-dimensional array 'stack' in element 'stp'. It is also decrementing 'stp'.
But which order does this happen in?
Does it return the value of element stp, then decrement stp?
Or does it decrement stp, then return the value of the element now referred to by the decremented stp?
If the code is:
int top()
{
return stack[stp-1];
}
Does it work any differently?
My apologies, I know this is very common coding style - I still have some trouble making sense of concise, uncommented code - even basics like this. Sorry.
It will decrement stp, and then return the value from the array at the location of the new stp value.
--stp is a "prefix decrement", and it is defined to decrement the argument (stp), and then return the new value. It has a counterpart called the "postfix decrement", stp--, which decrements stp and then returns the old value - so stack[stp--] will give you the value the current stp offset, but still decrement stp.
Finally, your version with stack[stp-1] will return the value from the same place as stack[--stp], but stp itself will be unchanged.
Simple answer: decrement first, then the array access.
More complicated answer: this code uses the prefix decrement operator, which is pre-decrement. This means that the the operator's result value, is the value after the decrement is performed.
Contrast this with the post-decrement operator. return stack[stp--]; would also decrement stp, but the index used would be the initial value.
For complex technical reasons which allow compilers maximum freedom to optimize, it isn't defined exactly when stp is modified. But what is certainly defined is that the value used as the array index is the value that stp would have, once decremented.
Your code for top() doesn't modify stp at all, but it's the same in the sense that the value it uses as the array index, is one less than the initial value of stp. So if you call top(), the value you get back is the same value you'll get next time you call pop().
--stp = Pre-decrement. stp is decremented BEFORE it's used.
stp-- = Post-decrement. stp is decremented AFTER it's used.
There are two versions of the decrement (and also increment) operator, like --i and i--. If you think of them as functions (which they are), the code would be (this assumes you know what operator overloading is, otherwise, see HERE).
// --i
int operator--() {
*this = *this - 1;
return *this;
}
// i--
int operator--(int i) {
int retVal = *this;
*this = *this - 1;
return retVal;
}
So, point being:
i-- returns the value BEFORE the decrement
--i returns the value AFTER the decrement
As for
int top() { return stack[stp-1]; }
This will return the index at one less than stp. However, because you haven't assigned a new value to stp, stp will be the same value after its done (which is probably not what you want).
return expression; means "evaluate the expression and return the result to the caller". You cannot have anything else happen after a function has returned to its caller. It is impossible to first return to the caller and then cause some side-effect.
Even if you had written return i++; or something, it would still have meant "evalute the expression i++ and then return the result to the caller". It just so happens that the result of i++ is the value that i had before it was incremented, but still, i was incremented. Simply think of i++ as (++i - 1).
There are two types of increment/decrement operations: prefix and postfix.
When use prefix operators, the the operation is executed firstly, then the access happens. In postfix the first is the access, the second is the operation.
So, in:
--stp;
stp will be decremented and then accessed.
if the code is return stack[stp-1], it works differently, namely that stp is not modified.
The instruction return stack[--stp]; works int he following way:
The expression to be returned is evaluated
The result of the evaluation is returned
Therefore, the value of stp is decremented.
As for your other other question, that is if
return stack[--stp];
is equivalent to
return stack[stp-1];
that depends of the nature of stp. If it is an automatic variable, the change of stp has no effect.