Chinaunix首页 | 论坛 | 博客
  • 博客访问: 10171
  • 博文数量: 11
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 120
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-19 09:55
文章分类

全部博文(11)

文章存档

2011年(1)

2010年(2)

2009年(8)

我的朋友
最近访客

分类: C/C++

2009-11-08 23:01:08

如果作以下声明:
 

char s[]="hello world";

char *p="hello world";


那么,以下语句是正确的:

s[3]='y';


但是,下列语句无法通过编译:

p[3]='y';



解释:
A string literal (the formal term for a double-quoted string in C source) can be used in two slightly different ways:
  1. 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).
  2. 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) |
0

上一篇:什么是Core Dump?

下一篇:float与double的区别

给主人留下些什么吧!~~