+ 2

C++ - Pointers strike again

Why with penultimate instruction (p = "XYZWVU") p changes, but s DOESN'T? #include <iostream> using namespace std; int main() { const char* p = "12345"; const char **q = &p; *q = "abcde"; cout << *p << endl; const char* s = ++p; cout << *s << endl; p = "XYZWVU"; cout << *++s; return 0; }

14th Sep 2019, 6:48 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
1 Resposta
+ 4
When you do const char* s = ++p; You are declaring a pointer s and pointing it at the second character within string literal "abcde". At this point, yes, p and s both point to the contents of the same string literal. Doing p = "XYZWVU"; however, does not alter the string literal pointed to by s. What this does is change what pointer p is pointing to. When you do this, pointer p and s are each pointing at different string literals.
14th Sep 2019, 7:15 AM
Hatsy Rei
Hatsy Rei - avatar