如果作以下声明:
char s[]="hello world";
char *p="hello world";
|
那么,以下语句是正确的:
但是,下列语句无法通过编译:
解释:
A string literal
(the formal
term
for a double-quoted string in C source)
can
be used in
two slightly different
ways:
-
As
the initializer for an array of char,
as in the
declaration of char a[]
,
it specifies the initial values of the characters in that array
(and, if necessary, its size).
- Anywhere else,
it turns into an unnamed,
static
array of characters,
and this unnamed array
may be stored in read-only memory,
and which therefore cannot necessarily be modified.
In
an expression context,
the
array is converted at once
to a pointer,
as usual,
so
the second declaration initializes
p
to point to
the
unnamed
array's
first element.
Some
compilers
have a switch controlling whether
string literals
are writable
or not
(for compiling old code),
and some
may
have options to cause string literals to be
formally
treated as arrays of const char
(for better error catching).
(摘自c-faq)
阅读(285) | 评论(0) | 转发(0) |