如何将数组地址赋给指针?

pok*_*che 0 c++ c++11

#include <iostream>

int main() {
  int arr[2] = {1, 2};
  int *p;
  // p = &arr; // Does not compile
  p = &arr[0]; // compiles
  std::cout << "&arr    = " << &arr << std::endl;
  std::cout << "&arr[0] = " << &arr[0] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试打印地址时,两者都打印相同的地址。但是当我尝试分配它时p = &arr,它无法编译。标准中是否有一些内容反对将数组地址分配给指针。我只是想知道为什么 p = &arr不能编译?

铿锵实际上说error: cannot initialize a variable of type 'int *' with an rvalue of type

R S*_*ahu 7

p = &arr;

是一个编译器错误,因为 的类型&arrint (*)[2]-- 指向“2 的数组int”的指针。因此,它不能分配给p类型为 的int*

尽管&arr&arr[0]计算出相同的数值,但它们是不同的类型。

  • 在 C 和 C++ 中,数组变量本质上是指向数组中第一项的指针。在谷歌上搜索“数组衰减”。 (3认同)