问题描述
当我们做
char *p ="house";
p = 'm';
它不允许的。
但是,当我们做
char p[] = "house";
p[0] = 'm';
printf(p);
它给O / P为:鼠标
It gives O/P as : mouse
我不能够理解的方式和其中C做内存分配的字符串常量?
I am not able to understand how and where C does memory allocation for string literals?
推荐答案
字符P [] =房子;
房子
是一个字符串存储在只读位置,但是,p是放在堆栈的字符在的数组房子
复制。
"house"
is a string literal stored in a read only location, but, p is an array of chars placed on stack in which "house"
is copied.
然而,在的char * p =房子;
, P
实际上指向只读位置其中包含字符串房子,从而改变它UB。
However, in char *p = "house";
, p
actually points to the read-only location which contains the string literal "house", thus modifying it is UB.
从标准的说明 6.7.8初始化
14字符类型的数组,可以用一个字符串被初始化
文字,可选大括号括起来。的连续字符
字符串文字(包括终止空字符,如果
有空间,或如果阵列是未知大小的)初始化
的数组的元素
所以你基本上字符数组。它不应该是那么困难或困惑你的理解,如果你使用了整数数组这个数组如何被修改
,浮动
等
So you basically have an array of characters. It should not be so difficult or puzzle you in understanding how this array gets modified if you have used arrays of ints
, floats
etc.
这篇关于C程序字符串字面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!