lokman said:
Please stop top-posting, and trim the quoted text down to the relevant
part. Read section 5 of the FAQ for posting guidelines.
I now understand that: During the while loop, pointer p is keep on changing
its memory address from the initial one which is point to character 't', up
to '\0'. That is the reason why after the while loop, if I put the statement
cout << p[5];, nothing will be return.
It's not accurate to say "nothing will be return". The behavior is
undefined. You cannot wildly index past the end of an array.
In odder to have point p to point to the start of the "test pointer"
characters, does it mean that I have to traverse p all the way back to where
it is pointing to initially (doesn't seem to work as I tested and doesn't
sound like a good practice) or should I reinitialize the p to point to "test
pointer again" ?
If you iterate backward, how will you know when you've reached the
beginning? The smart thing to do would be to save your original pointer
if you still need it:
const char * const the_string = "some literal";
const char *p = the_string;
// now use 'p' however you want
p = the_string;
You could reassign the same literal again, but 1) it's not guaranteed to
be the same address and 2) duplicating parts of the code like that leads
to problems later. When you change one, you have to be sure to change
the other, and it's not obvious that the two are related.
Actually, I have modified the previous code to become a version where I can
guarantee to get char number 6 before and after the while loop, please give
some comment.
Thanks a lot.
#include <iostream>
using namespace::std;
int main() {
char chr[] = "test pointer";
const char *p = chr; // constant character pointer to avoid chr[] content
being change
Just so we're clear, you don't *need* to have 'const' here -- that is,
it would not be an error (from the language's point of view) if you
modified the thing p points to. If it's not what you want your program
to do, that's fine. But you could if you wanted to.
cout << p[5] << endl; // this prints p
cout << chr[5] << endl; // this prints p too !
while (*p) { cout << *p; ++p;}
cout << endl;
cout << chr[5] << endl; // this prints p after the while loop
cout << p[5] << endl; // this doesn't print the 6th char anymore
This gives undefined behavior.
-Kevin