【问题标题】:Why value at operator(*) not work when the pointer is pointing to an array?当指针指向数组时,为什么 operator(*) 的值不起作用?
【发布时间】:2022-01-22 01:24:30
【问题描述】:

我有以下两个代码 sn-ps 将一个数组复制到另一个数组中,用 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];
    }

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

【问题讨论】:

  • 因为*ptr[i]*(ptr[i]) 相同。事实上,由于对于任何指针或数组ptr 和索引i,表达式ptr[i] 完全 等于*(ptr + i),因此解引用内置于数组索引中。所以*ptr[i] 将是*(*(ptr + i)),这是一个取消引用太多了。

标签: c pointers syntax


【解决方案1】:

让我们一步一步来。

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

【讨论】:

  • *ptr[i] would attempt to reference the integer value - 没有它的语法错误,因为您不能在将整数值转换为指针类型之前取消引用它,例如:*(int *)ptr[i]
  • 是的,我不够清楚,但这就是我试图通过“尝试”来表达的意思。
猜你喜欢
  • 1970-01-01
  • 2011-12-16
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
  • 2018-01-03
相关资源
最近更新 更多