Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return to the beginning of a pointer?

Tags:

c++

pointers

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

like image 368
Brett Avatar asked Dec 09 '22 10:12

Brett


2 Answers

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.

like image 95
Chris Lutz Avatar answered Dec 21 '22 07:12

Chris Lutz


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.

like image 32
AnT Avatar answered Dec 21 '22 06:12

AnT