
www.Usenet.com
| <-- __Chronological__ --> | <-- __Thread__ --> |
[EMAIL PROTECTED] (Joe Developer) wrote
> This code crashes at run time with a memory fault on the assignment
> statement. I tried it under MSVC 6 and GC++. It worked in Borland C
> many years ago. Boy do I feel stupid.
>
> void main()
> {
> char *foo = "Hello World";
> foo[0] = '9'; //crashes here.
> }
The string "Hello World" sets aside 12 bytes (including the null
byte) in a READ-ONLY section of memory. The data type of the string
is char*, but that's only because so much legacy code (especially
in C, as opposed to C++) expects it that way. The data type really
ought to be const char*, because you are not allowed to write into
it.
(By the way, if you had tried this in Borland C:
for (i=0; i<2; ++i) {
char *foo = "Gello World";
++*foo;
cout<<foo<<endl;
}
You would have gotten
Hello World
Iello World
because you're modifying the one-and-only copy of the string!)
Try this instead:
char foo[] = "Hello World"; // This COPIES the 12 bytes
foo[0] = '9'; // No problem now
You can do this as often as you need, because now you're only
modifying a copy.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
| <-- __Chronological__ --> | <-- __Thread__ --> |