cplusplus.com cplusplus.com
cplusplus.com   C++ : Forums : General C++ Programming : Pointer Madness
  Search:
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forums
Forums
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programm...
Articles
Lounge
Jobs

-

post  Pointer Madness

g0dwyn (70)
Hi forum,

So the latest in my perplexing programming issues is this: I've got an integer pointer that points to a valid variable, like so:

1
2
int bar = 0;
int *foo = &bar;


And later on in the code I increment the dereferenced pointer, like so:

*foo++;

Now I looked in my debugger when the program started to not work, and I noticed that it wasn't the value that was incrementing, but the pointer; bar had jumped from 0 to 5, and the address of *foo had changed. What did I miss here? Do increments not work with derefenced pointer values?

Thanks in advance, everyone.
|
firedraco (848)
I don't remember the ++ and the deference operator precedences...so try this:

(*foo)++;
| Last edited on
exception (321)
*x++ is shorthand for
x->operator++(int)->operator*()
Now the postincrement returns the old value of x, therefore, it is similar to (if postincrement is implemeted as one would expect, that is, which is the case with all built-in-types and stl iterators):
1
2
3
int* tmp = x;
++x;
*tmp;

...so as you can see x is incremented (*not* the value pointed to by x) and the dereferencing operator has no effect whatsoever (except the pointer to is not valid, in which case you invoke undefined behavior).
The solution for what you want was already posted.
|

This topic is archived - New replies not allowed.
Home page | Privacy policy
© cplusplus.com, 2000-2009 - All rights reserved - v2.2
Spotted an error? contact us