数组被视为常量指针,因此我们无法更改指针值,我无法想象我们假设 -
a[5]="hello";
a="hai"; // I Know This not possible but why if below a[0]='a' is possible?
a[0]='a' ;//this is possible because a is store in stack memory.
Run Code Online (Sandbox Code Playgroud)
现在来指针
char *a="hello";
a="hai"; //i know this is possible because string are store in code section which is read only memory then why it is changed?
a[0]='a' //Not possible because it is store in stack and string is store in code section if above a="hai" is possible then why a[0]='a' is not possible?
Run Code Online (Sandbox Code Playgroud)
我是新来的,我被封锁了两次,所以除了通过投票失败而道德败坏之外,请帮助我理解这个概念
数组被视为常量指针
不,它不是这样对待的.数组被视为...数组.
a="hai"; // I Know This not possible but why
Run Code Online (Sandbox Code Playgroud)
因为语言定义是这样说的(更确切地说,因为数组不是可修改的左值).它之所以如此,是因为它没有意义.
您对"堆栈"和"代码"的评论不相关; 数组中对象的可修改性不依赖于它们的存储位置.这是一个实现细节.
假设以下声明:
char arr[6] = "hello";
char *ap = "hello";
Run Code Online (Sandbox Code Playgroud)
这是一个可能的内存映射,显示了这些声明的结果(所有地址都是凭空而构成的,并不代表任何真实的架构):
Item Address 0x00 0x01 0x02 0x03
---- ------- ---- ---- ---- ----
"hello" 0x00008000 'h' 'e' 'l' 'l'
"hai" 0x00008004 'o' 0x00 'h' 'a'
0x00008008 'i' 0x00 0x?? 0x??
...
arr 0x82340000 'h' 'e' 'l' 'l'
0x82340004 'o' 0x00 0x?? 0x??
ap 0x82340008 0x00 0x00 0x80 0x00
Run Code Online (Sandbox Code Playgroud)
字符串文字"hello"存储为6元素数组,char其地址为静态存储持续时间0x0008000.字符串文字"hai"存储为4元素数组,char其地址为静态存储持续时间0x00080006.字符串文字的内容可以被存储在存储器的只读部分(取决于平台).尝试修改字符串文字内容时的行为未定义 ; 代码被认为是错误的,但编译器不需要以任何特定方式处理该情况.您可能会遇到段错误,或者根本不会应用更改,或者更改将按预期应用.我假设源代码中的字符串文字的多个实例将映射到内存中的单个实例(这是通常的情况IME).
除非它是sizeof或一元运算&符的操作数,或者是用于初始化声明中的另一个数组的字符串文字,否则"N元素数组T" 类型的表达式将被转换("衰减")为表达式输入"指向T",表达式的值将是数组第一个元素的地址.结果指针是不可修改的左值.
声明
char arr[6] = "hello";
Run Code Online (Sandbox Code Playgroud)
声明arr为char具有自动范围的6元素数组,并将字符串文字的内容"hello"复制到其中.您可以arr[0]通过arr[5]所有想要修改的值,以便您可以编写
a[0] = 'a';
Run Code Online (Sandbox Code Playgroud)
但你不能写像
arr = "hai";
Run Code Online (Sandbox Code Playgroud)
因为当两个表达式的arr和"hai"如上所述被转换为指针值,arr 不是指针变量 ; arr除了数组元素本身之外没有相关的存储空间,所以没有地方可以分配"hai"(0x00008006)的结果.
声明
char *ap = "hello";
Run Code Online (Sandbox Code Playgroud)
声明ap为char的指针,并将表达式的结果赋给"hello"它.在这种情况下,字符串文字不是sizeof或一元运算&符的操作数,并且它不用于初始化数组的内容,因此它被转换为指针表达式,其值是第一个的地址数组的元素,或0x0008000.
这几乎与镜像相反arr; 你无法更新ap[0]通过的内容ap[5],但你可以为其分配一个新的指针值ap,所以
ap = "hai";
Run Code Online (Sandbox Code Playgroud)
作品.这样做之后,你的内存映射就会像
Item Address 0x00 0x01 0x02 0x03
---- ------- ---- ---- ---- ----
"hello" 0x00008000 'h' 'e' 'l' 'l'
"hai" 0x00008004 'o' 0x00 'h' 'a'
0x00008008 'i' 0x00 0x?? 0x??
...
arr 0x82340000 'a' 'e' 'l' 'l'
0x82340004 'o' 0x00 0x?? 0x??
ap 0x82340008 0x00 0x00 0x80 0x06
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
478 次 |
| 最近记录: |