现在的位置: 首页 > 综合 > 正文

浅析字符常量区

2013年09月16日 ⁄ 综合 ⁄ 共 388字 ⁄ 字号 评论关闭

以下程序编译环境为gcc

1.

#include <stdio.h>
#include <string.h>

int main()
{
	char* s1 = "Hello";
	s1[0] = 'z';
	printf("%s\n",s1);
	return 0;	
}


编译不会出错,但运行错误Segmentation fault。因为字符串"Hello"在字符常量区,指针s1指向字符常量区,字符常量区是不可更改的,所以(s1[0] = 'z') 这一步错误。
其实,char* s1 = "Hello" 等价于 const char* s1 = "Hello" 
2.

#include <stdio.h>
#include <string.h>

int main()
{
	char s2[] = "world";
	s2[0] = 'z';
	printf("%s\n",s2);
	return 0;	
}

这段程序运行正确。字符串"world"存储在数组s2里,在栈空间中,可以进行修改。

抱歉!评论已关闭.