Should'nt this work since I am modifying only one memory location.
No, it shouldn't work because string literals aren't modifiable.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
This will work ok because it isn't trying to change a string literal
char s[] = "hello world";
*(s+1) = 'a';
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
Ancient Dragon is correct. In your original example, s is a char*, but string literals are const char*, and non-mutable - usually the compiler assigns them to read-only memory. The way that AD did it, to declare s as an array, means that the compiler will take the string literal as an initializer for an array that is in writable memory. IE, it gives the same result as this:
char s[12] = { 'h','e','l','l','o',' ','w','o','r','l','d',0 };
but the way AD did it is a LOT easier!
rubberman
Posting Virtuoso
1,564 posts since Mar 2010
Reputation Points: 277
Solved Threads: 179
Enable ISO C++ conformance (eg. --std=c++0x -pedantic) and warning messages (eg. -Wall).
char * s = "hello world";
would have made the compiler emit a diagnostic - something like
"warning: deprecated conversion from string constant to char*".
vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287