c - 为什么对带下标的数组的赋值有效,而对取消引用的指针算术表达式的赋值却无效?

标签 c arrays pointers pointer-arithmetic

Kernighan & Ritchie 第 2 版。说:

The correspondence between indexing and pointer arithmetic is very close. By definition, the value of a variable or expression of type array is the address of element zero of the array. Thus after the assignment
pa = &a[0];

pa and a have identical values. Since the name of an array is a synonym for the location of the initial element, the assignment pa=&a[0] can also be written as
pa = a;

Rather more surprising, at least at first sight, is the fact that a reference to a[i] can also be written as *(a+i). In evaluating a[i], C converts it to a[i] immediately; the two forms are equivalent. Applying the operator & to both parts of this equivalence, it follows that and are also identical: a+i is the address of the i-th element beyond a. As the other side of this coin, if pa is a pointer, expressions may use it with a subscript; pa[i] is identical to *(pa+i). In short, an array-and-index expression is equivalent to one written as a pointer and offset.

阅读本文后,我希望这两个程序的工作方式相同:

/* Program 1 */
#include <stdio.h>


int main()
{
    char arr[] = "hello";
    arr[0] = 'H';
    printf("%s\n", arr);

}

/* Program 2 */
#include <stdio.h>


int main()
{
    char *arr = "hello";
    arr[0] = 'H';
    printf("%s\n", arr);

}

但实际上只有第一个有效。对于第二个,我遇到了段错误。

为什么?非常感谢引用权威来源。

最佳答案

当您定义和初始化数组时,所有数组都分配在可修改的内存(通常是堆栈)中,因此您可以随意修改数组。

当您使用字符串文字时,编译器将为您提供一个指向只读 零终止char 数组的指针。尝试修改此数组(您在第二个示例中所做的)会导致未定义的行为

关于c - 为什么对带下标的数组的赋值有效,而对取消引用的指针算术表达式的赋值却无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32099660/

相关文章:

c - 位移位和整数提升?

arrays - 如何比较特定索引处单独数组的元素?

javascript - 从一系列对象构建家谱

java - 如何在java中排队并调用实际方法(而不是立即评估)?

c - 从c中的文本文件中读取列的算法

c - C中实现mac地址表条目老化的数据结构

c - 如何跳过多维数组中的行

c - 在 C 中初始化 2D/3D 数组的简写方法?

chdir(..) 成功返回 0 并更改目录,但输出 "No such file or directory"

c - 指向c中许多结构的指针