char *p="abcdef"和char s[]="abcdef"存储在哪里的问题!

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.

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值