|
发表于 2006-1-11 13:03:08
|
显示全部楼层
似乎C语言中用字符串常量给char*变量复制的时候是先创建字符串常量,再将地址赋值给变量。
- $ cat const.c
- #include <stdio.h>
- int main()
- {
- const char* s1 = "test";
- char* s2 = s1;
- printf("%s\t%d\n%s\t%d\n", s1, s1, s2, s2);
- s2 = "modified";
- printf("%s\t%d\n%s\t%d\n", s1, s1, s2, s2);
- return 0;
- }
- $ gcc -Wall -o const const.c
- const.c: In function ‘main’:
- const.c:6: warning: initialization discards qualifiers from pointer target type
- const.c:7: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘const char *’
- const.c:7: warning: format ‘%d’ expects type ‘int’, but argument 5 has type ‘char *’
- const.c:9: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘const char *’
- const.c:9: warning: format ‘%d’ expects type ‘int’, but argument 5 has type ‘char *’
- dxy@dengxy:~/Projects/test$ ./const
- test 134513976
- test 134513976
- test 134513976
- modified 134513994
复制代码
因此,用s1给s2赋值,s2指向s1指向的地址;而用字符串常量给s2赋值之后s2应指向新的字符串常量的地址。因此楼主的情况显然是不正常的。
难道gcc 3.2.3不符合C标准? |
|