Re: char *
- From: "Igor Tandetnik" <itandetnik@xxxxxxxx>
- Date: Fri, 4 Apr 2008 20:51:07 -0400
"Carmen Sei" <fatwallet951@xxxxxxxxx> wrote in message
news:r4gdv3lrrv3s93fr20mtnb5u6rsk0sj5n8@xxxxxxx
why the following compile is OK
but will crash when execute?
String literals (like "abcd") should not be modified. VC compiler
actually stores them in a block of memory marked read-only, so any
attempt to modify them generates a hardware exception (what you call a
crash).
For backward compatibility with C, a string literal (whose type,
formally, is an array of const char) can be implicitly converted to
char*, which gives a false impression that it can in fact be written to.
It can't. Don't do that.
String literals should not be confused with a special form of
initializer that can be used for char arrays:
char* p = "abcd"; // string literal
char arr[] = "abcd"; // initializer
The latter is simply a more compact form of this equivalent statement:
char arr[] = {'a', 'b', 'c', 'd', '\0'};
Character arrays can of course be modified (whether initialized with
what looks like a string literal but isn't, or otherwise).
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925
.
- Follow-Ups:
- Re: char *
- From: Alex Blekhman
- Re: char *
- References:
- char *
- From: Carmen Sei
- char *
- Prev by Date: Re: pointer vs reference
- Next by Date: Re: pointer vs reference
- Previous by thread: Re: char *
- Next by thread: Re: char *
- Index(es):
Relevant Pages
|