int main() {
char **k;
char *s ="abc";
char *b ="def";
k = &s;
k++;
k = &b;
cout<<*(k - 1)<<endl; // nothing but newline. Shouldn't I get "abc"?
//EDIT: corrected a typo should be *(k - 1)
}
I got nothing but a newline from cout. When I looked at the behavior of char* I get the impression that since I have the address of of the first character I could use char* like an array, which is true. However, for char** this behavior seems to be totally different, when I tried k++ it doesn’t seem to behave like an array. Why is that?
Also when I tried (K + 1) = &b; I got an error, why couldn’t I do that?
kis a pointer to a pointer to a char, so when you advance it, it does not walk down the string as you’re expecting it to. Instead, it now points to thechar *that is located adjacent to the one it was pointing to. In your case there is none, so you’re de-referencing a random memory location when you print the value of*(k - 1).The above is an error because you must have an l-value on the left side of an assignment, it cannot be a temporary expression (r-value).
EDIT:
Here’s an example that’ll hopefully be easier to follow than reading about the mistake you’ve made.