char *p="abcdef"; //"abcdef" 静态存储区,是常量区,不可改, p[2]企图通过p这个指针改变常量区的内容,所以你这个程序编译通过,运行会出错
char s[]="abcdef";//"abcdef" 静态存储区, 你赋值给s[]这个变量后,改变s[2],所以不出错。
p, s 在同一个区,如果是局部变量,就是在栈里面。
"abcdef"; //静态存储区,是常量区,不可改
char *p="abcdef"; 只是将p指向了该字符串常量而已
char s[]="abcdef"; 在栈上分配了字符串数组,并且将字符串常("abcdef")量的值拷贝到该数组中
,该数组的值是可以修改的,但其被没有修改原来的字符串常量
1.32: What is the difference between these initializations?
char a[] = "string literal";
char *p = "string literal";
My program crashes if I try to assign a new value to p[i].
A:A string literal can be used in two slightly different ways. As
an array initializer (as in the declaration of char a[] in the
question), it specifies the initial values of the characters in
that array. Anywhere else, it turns into an unnamed, static
array of characters, which 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 (see section 6), so the second declaration initializes
p to point to the unnamed array's first element.
(For compiling old code, some compilers have a switch
controlling whether string literals are writable or not.)
See also questions 1.31, 6.1, 6.2, 6.8, and 11.8b.
References: K&R2 Sec. 5.5 p. 104; ISO Sec. 6.1.4, Sec. 6.5.7;
Rationale Sec. 3.1.4; H&S Sec. 2.7.4 pp. 31-2.