转自:jianchi88 http://blog.csdn.net/jianchi88/article/details/6876405
#include<stdio.h> int main() { char a[] = "hello world1"; char *p = "hello world2"; *(a+1)='q'; *(p+1)='q'; printf("%s ",a); printf("%s ",p); }
运行结果
段错误。
注释 *(p+1)='q';
运行结果
hqllo world1
hello world2
原因:
一、a与p类型不同:p为指向字符串的指针;a为保存字符串的数组。
char a[] = "hello world1"; 是个赋初值的字符数组。
char *p = "hello world2"; 是个字符串常量指针;
指针变量p在栈里面
字符串常量"hello world2"在全局数据区,数据段,只读,不可写
二、"hello world2"和"hello world1"字符串保存的位置不同。"hello world1"保存在栈
中,可用*(a+1)='q'修改,"hello world2"保存在全局数据
区,位置是在.rodata中,不能修改*(p+1)='q'
三、只有2中情况下,数组名不可等同视为数组指针,&与sizeof操作符
“&”的区别:
&p取得是指针变量的地址,而非字符串"hello world2"的首地址,p指向字符串的首地址;&a取得
就是字符串"hello"的首地址。
“siziof”的区别:
下面假设在ia32平台上运行,保存变量的内存空间不同。
sizeof(p); // return 4, pointer size
sizeof(a); // return 13, array size
5 char a[] = "hello world1"; (gdb) p a $1 = "