这段代码、数组和指针的输出是什么

What is the output of this code, array and pointers

我对下面的代码有几个问题。

  1. 如果我有某种类型的指针,对它使用数组索引意味着什么?在这个例子中,ptr[3] 代表什么(ptr 是某种类型的指针)?
  2. 程序的输出应该是 to be or not to be (Hamlet) 但我不确定为什么,我的问题是行 (&ptr2)[3] = str,我不明白怎么办此行更改 ptr1 数组的第三个元素。

    int main()
    {
     char str[] = "hmmmm...";
     const char *const ptr1[] = {"to be", "or not to be", "that is the question"};
     char *ptr2 = "that is the question";
    
     (&ptr2)[3] = str;
    
     strcpy(str, "(Hamlet)");
     for (int i = 0; i < sizeof(ptr1) / sizeof(*ptr1); ++i)
     {
        printf("%s ", ptr1[i]);
     }
     return 0;
    }
    

使用 this 可视化工具,我们可以看到 ptr1 将指向 str,我只是不明白为什么会这样。

感谢帮助。

If I have a pointer of some type, what does it mean to use array indexing with it? in this example, what does ptr[3] stand for (ptr is a pointer of some type)?

在C语言中,a[i]*(a + i)的语法糖。这是指针的有效语法,即使它们不指向数组。

The output of the program is supposed to be to be or not to be (Hamlet) but I am not sure why, my problem is with the line (&ptr2)[3] = str, I don't understand how does this line changes the third element of the ptr1 array.

(&ptr2)[3] 没有改变 str1 中的任何内容。它试图访问未知的内存位置。

如果有人告诉您该程序的输出应该是 "to be or not to be (Hamlet)",那您就错了。