I know that you can take a po开发者_如何转开发inter 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.
The easiest method is to use another value to save the original 0 index. I don't think you can actually address the "first" unless it's in like a sorted data structure.
You can't, not without counting, since it is a pointer so when you increment the pointer you are effectively leaving the spot it was pointing to losing that info.
Compare with
int a[10] = {0};
int *p = NULL;
p = a; // start of array
++p; // p points to a + 1
++p; // p points to a + 2,
// .. but there is no intrinsic information in 'p' where start of 'a' is.
精彩评论