I know that you can take a pointer such as:
someFunction(const char* &txt)
{
txt++; //Increment the pointer
txt--; //Decrement the pointer
}
how do I get back to the beginning of the pointer? (without counting my number of increments and decrementing that amount) I was thinking about something like:
txt = &(*txt[0]);
But that isn't seeming to work (assigning the pointer to its beginning location).
Any help would be greatly appreciated
Brett
You can't. You have to either save it's original position:
const char *o = txt;
// do work
txt = o;
Or use an index:
size_t i = 0;
// instead of txt++ it's i++
// and instead of *txt it's txt[i]
i = 0;
Your attempt:
txt = &(*txt[0]);
Is incorrect, if you look at it. First, it takes txt[0]
(which is of type char
), then tries to dereference it with *
, and then takes that address with the &
operator (theoretically yielding the original result, though I wouldn't want to think too hard about whether this works for dereferencing arithmetic types like char
), then assigns that (arithmetic) result to a pointer. It's like you're saying:
const char *txt = 'a';
It doesn't make sense. What you probably were looking for was simply
txt = &txt[0];
which, at first glance, might look like it's setting txt
to point to the first element of txt
, but keep in mind that txt[0]
is just *(txt + 0)
, or *txt
. And &*txt
simplifies to txt
, so you're effectively doing:
txt = txt;
Or nothing. You get the same pointer. Use one of the two methods I described.
A pointer does not have a "beginning". Ever time you increment a pointer (or decrement, or change in any other way), you get a new, completely independent pointer value, which has no "memory" of the old pointer value and no relation to the old pointer value.
If you need to restore the old pointer value, you have to either memorize the value or memorize the changes (so that you can roll them back later). There's no other way to restore the old value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With