【问题标题】:&(array+1) gives compilation error while &arr works&(array+1) 在 &arr 工作时给出编译错误
【发布时间】:2019-02-24 22:08:53
【问题描述】:

在下面的代码中-

(考虑到这段代码包含在主函数中,并带有所有必要的标题)

int arr[5] = {10,20,30,40,50};

cout << &(arr);

cout << &(arr+1);

如果我们只保留第一个 cout,它会工作并打印数组的起始地址。

但是如果我们保留第二个 cout 则会出现编译错误。

为什么会这样?

【问题讨论】:

  • @pmg 你是说&amp;(arr + 1) 应该用C 编译,还是说需要printf 用C 打印东西?
  • “如果我们保留第二个 cout,它会产生编译错误。” - 你是说报告的错误完全无法理解吗?在发布有关错误(尤其是编译错误)的问题时,始终发布错误消息逐字within your question 以及您认为它的含义或您遇到的错误信息的哪些部分难以理解,因为它们与您的代码相关。

标签: c++ arrays pointers address-operator


【解决方案1】:

因为&amp; 正在获取一个左值 的地址,即一个对象。

arr 是对应于数组的左值。这就是第一个有效的原因。但arr+1 不是。这是一个临时结果(顺便说一下,它已经对应于一个地址)。

如果要获取地址,不出现编译错误,可以使用以下方法之一:

cout << arr+1 <<endl;      // get address directly using pointer maths
cout << &arr[1] <<endl;    // gets address of an element in the array
cout << &*(arr+1) <<endl;  // long and painful:  transform an address in a pointr
                           // and back again.  Better use the first alternative

这里是online demo。对了,第一个可以简化为cout&lt;&lt;arr&lt;&lt;endl;

【讨论】:

【解决方案2】:

为什么会这样?

将整数添加到指针 是一个产生新值的表达式。表达式的值类别是右值。

地址运算符的操作数必须是左值。右值不是左值。您不能获取返回新值的表达式的地址。


有点不清楚您要做什么。以下是一些表达式示例:

&(arr[0])   // address of the first element
arr + 0     // same as above

&(arr[1])   // address of the second element
arr + 1     // same as above

&arr        // address of the array.
            // note that type of the expression is different,
            // although the value is same as the first element

(&arr) + 1  // address of the next array (only valid if arr is
            // a subarray within a multidimensional array
            // which is not the case in your example)

&(arr+1)    // ill-formed; has no sensical interpretation

arr 不是指针;它是一个数组。但是数组衰减为指向使用该值的表达式中第一个元素的指针,因此在这种情况下,表达式的类型确实是数组指针转换后的指针。

【讨论】:

  • 您能详细说明“arr 不是指针”和“数组衰减为指针”吗?我一直认为数组是初始化多个顺序指针的一种方式。我错了吗?
  • @BasinhetVeld 我很确定你错了,尽管我什至不太明白 “初始化多个顺序指针” 是什么意思。数组和指针是具有不同属性的不同事物。首先是连续存储位置中的一系列对象;后者是指向另一个对象的对象。数组指针衰减在许多情况下确实使数组名称在许多情况下的行为与指针非常相似,因为转换后的确实是指针。
  • @errorika 我的意思是(但没有说得很好)是这样的指针: int* p = (arr + 0);可以像 arr 变量一样使用 - p[0], (p + 0) 做同样的事情。但这正是因为腐烂。感谢您的澄清
猜你喜欢
  • 2019-07-06
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
  • 2023-03-26
相关资源
最近更新 更多