|  | 
沙发
 
 
 楼主|
发表于 2009-7-10 15:09:39
|
只看该作者 
const 字符串 与 const 指针
| 有错误的代码: 
 编译时提示:#include <stdio.h>
 int main()
 {
 const char *arg = "hell world!";
 char const *p = "new world!";
 char *const q = "old world!";
 printf("%c\\n", *arg);
 arg++;
 printf("%c\\n", *arg);
 *arg = 'X';
 printf("%c\\n", *arg);
 
 printf("%c\\n", *p);
 p++;
 printf("%c\\n", *p);
 
 printf("%c\\n", *q);
 q++;
 printf("%c\\n", *q);
 
 
 return 0;
 }
说明:beyes@linux-beyes:~/C> gcc -g const.c -o const.execonst.c: In function ‘main’:
 const.c:11: error: assignment of read-only location ‘*arg’
 const.c:19: error: increment of read-only variable ‘q’
char const *p = "new world!";
 char *const q = "old world!";
 上面的两个定义是一样的。
 
 编译出错中的第一行,是因为 const 字符串为常数字符串,字符串中的元素不能更改,像上面想把 e 字符改成 X 就不行,会报错。然而指向字符串的指针(arg)可以移动。
 
 像 char *const q = "old world!"; 这种定义,是定义了一个 const 指针,它本身所指向的非 const 字符串中的元素可以改变,但自己自身不能移动,可以将其复制给另外一个非 const 的指针来进行字符串的修改。
 | 
 |