In article <news:Pi******************************@unix.cs.tam u.edu>
Bo Sun <b0*****@cs.tamu.edu> writes:
char* hello = "Hello World\n";
hello[5] = 's';
[does not work; why not?]
Others have already posted correct answers (which boil down to
"because the C standard says it does not have to work", and in your
case your C compiler makes sure it does not work), but I want to
clarify one bit. The thing with the double quotes above *is* a
"string literal", in the Standard's terminology, but the array to
which "hello" points is not actually a "string literal".
String literals are purely source-code constructs, rather like
keywords. If you write "int x, y;" then x and y have type "int",
but there is no requirement -- and often no actual -- run-time
information lying around saying "this memory over here is what was
originally named x, and has type int". One can reverse-engineer
object code and often figure out that "there is an int or long in
this memory over here", but perhaps not which one it is (int or
long), and in most cases, there is no way at all to recover the
name of the variable.
In any case, the anonymous array that the string literal produces
in this context has type "array 12 of char", rather than the more
logical "array 12 of const char". If you apply The Rule about
arrays and pointers in C (see
http://web.torek.net/torek/c/pa.html),
you will find that "array 12 of char" is usable wherever a value
of type "char *" is required. Thus, this is a valid initializer
for the variable "hello" -- but the array's elements are allowed
to be, and your compiler makes them, read-only.
Note that when a string literal is used as an initializer for an
object of type "array N of char", the string literal does not (or
at least need not) produce any array of its own, and the characters
inside the string literal are used instead to initialize the object.
The "const"-ness (i.e., readonly-ness) of the object is then
controlled by the object's type: if it is "array 12 of char" it is
read/write; if it is "array 12 of const char" it is read-only.
I wrote a long article about this just a week or so ago.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.