【问题标题】:Getting error while assiging array of interger to interger pointer [duplicate]将整数数组分配给整数指针时出错[重复]
【发布时间】:2021-03-12 18:25:51
【问题描述】:

我需要了解编译错误。

int main(int argc, char *argv[])
{

  int yocto[] = {100, 200, 300, 400};
  
  int *android = &yocto; // Getting error cannot convert ‘int (*)[4]’ to ‘int*’ in initialization

  int *linux = yocto; // Working fine.

  // But when I am printing the value of &yocto and yocto giving same address.

  cout<<"Value of &yocto : " <<&yocto<<endl; // 0x7ffc5f553e50

  cout<<"Value of yocto  : "<<yocto<<endl;  // 0x7ffc5f553e50

  return 0;

}  

请解释一下编译器在内部使用&amp;yocto 地址做什么。

【问题讨论】:

  • 想象一下像激光笔一样的指针。您可以指向ints、数组、结构等...是绿色的,.., ..., .... 现在计算数组{ 1, 2, 3, 4 } 和一个指向数组的绿色指针,同时还有一个指向数组第一个元素的红色指针。指针指向同一个地方吗? :-)
  • 改写为,“为什么int[4] 可以衰减为int*,而int(*)[4] 不能?”可能有重复。应该澄清的是,这两行都试图从一种类型转换为另一种类型。
  • 您的int *android = &amp;yocto; 应该是int *android = &amp;yocto[0]; 否则您将数组的地址分配给整数的地址。数组不是整数。

标签: c++ arrays pointers compiler-errors


【解决方案1】:

yocto 是一个数组,但是当用作参数分配给指针时,它会衰减为指向数组第一个元素的指针。 &amp;yocto 是指向数组的指针。具体来说,指向4元素的int数组的指针,因为这就是yocto,所以&amp;yoctoint (*)[4]的类型

【讨论】:

  • 我仍然对答案感到困惑,如果我们打印 &yocto 的地址,yocto 两个地址是相同的。 cout
  • 物理位置相同,但类型不同。就像结构的第一个成员的地址与结构的地址相同,但是如果您在它们上使用地址运算符(&amp;),它们将具有不同的数据类型。 (至少在 C 中是这样;不确定 C++ 中的结构基本上是类)。
猜你喜欢
  • 2014-08-03
  • 2018-08-24
  • 1970-01-01
  • 2017-02-12
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多