当指针指向数组时,为什么 value at operator(*) 不起作用?

Why value at operator(*) not work when the pointer is pointing to an array?

我有以下两个代码片段,用 C 编写的 VS 代码将一个数组复制到另一个数组中:

片段 1 ~

int arr[5]={1,2,3,4,5};
int arr_copy[5];
int *ptr = arr;
for(int i=0; i<5;i++)
{
    arr_copy[i]=*ptr[i];
}

片段 2~

    int arr[5]={1,2,3,4,5};
    int arr_copy[5];
    int *ptr=arr;
    for(int i=0; i<5;i++)
    {
        arr_copy[i]=ptr[i];
    }

第一个片段在编译时抛出错误,指出 *ptr[i] 无效,但第二个片段有效。第一个不应该 return 存储在指针 ptr[i] 的值而第二个应该 return ptr[i] 的整数地址吗?它只是 C 语法的编写方式还是背后有一些逻辑?

让我们一步一步来。

  1. ptr是指向arr的第一个元素的指针。
  2. ptr[i] 等同于 *(ptr+i),或者在这种情况下 arr[i]
    • 你看,幕后有一个隐式的取消引用操作。
  3. *ptr[i] 将尝试引用存储在数组中的 整数值 ,即从任意位置读取内存。这几乎总是会失败。