pointers to chars
Well see the above code
int a = 10;
int* p1 = &a;
int* p2 = p1; // Copies the address right?
But what happens here?
char* str1 = "Hello";
char* str2 = str1; // What happens here
I tried this code and when I modified str1, str2 remain unchanged why?
One more thing, if I initialize something else to str1 i.e.
char* str1 = "Hello";
str1 = "Hell";
What happens here? Is the "Hello" string deleted and space for new string is accommodated?
manzoor
Junior Poster in Training
54 posts since Nov 2007
Reputation Points: 12
Solved Threads: 3
What happens - see my post in the recent thread http://www.daniweb.com/forums/thread156711.html .
You can't modify string literal via pointers, on modern platforms you catch memory access exception. So in your 2nd snippet str2 points to the same C-string literal address - that's all. If you modify str1 value (for example, str1 = "Bye"; ), it does not bear a relation to its original target (->"Hello") or another pointer variable str2 value.
Pointers str1 and str2 are variables which contain addersses. If you change these variables these actions do not change old adressed objects. The last snippet: now str1 points to "Hell", that's all. Nobody remember that it was referred to "Hello" (both "Hello" and "Hell" chars are placed in read-only memory).
Don't mix up pointers to char (as usually treated as pointers to C-strings) with std::string class objects. Last ones are not pointers!
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
Of course, all good C++ implementations "prevent modification for chars that are const". All char literals placed in read-only address subspace. The C++ Standard forbid to modify text literals. However it's possible (but illegal) in old DOS implementations (BC++, for example): no hardware support for read-only memory in DOS.
char str1[] = "Hello";
char* str2 = str1;
It's totally different case: ordinar char array is defined. You can modify its contents.
Yet another tip about pointers to C-string literals in C++:
const char* p1 = "Hello";
const char* p2 = "Hello";
cout << (p1==p2? "Yes" : "No!") << endl;
This program may print Yes or No! - both cases are correct! The second occurence of "Hello" literal may denote the same or different memory address. It's an implementation-defined issue.
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348