C++ &;(数组+;1)在&;arr工程
在下面的代码中- (考虑此代码包含在主功能中,并带有所有必要的标题)C++ &;(数组+;1)在&;arr工程,c++,arrays,pointers,address-operator,C++,Arrays,Pointers,Address Operator,在下面的代码中- (考虑此代码包含在主功能中,并带有所有必要的标题) int-arr[5]={10,20,30,40,50}; cout,因为&使用左值的地址,即对象 arr是与数组相对应的左值。这就是第一种方法有效的原因。但是arr+1不是。这是一个临时结果(顺便说一下,它已经对应于一个地址) 如果要获取地址而不出现编译错误,可以使用以下选项之一: cout << arr+1 <<endl; // get address directly using poin
int-arr[5]={10,20,30,40,50};
cout,因为&
使用左值的地址,即对象
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
cout
为什么它会这样做
将整数添加到指针†是一个产生新值的表达式。表达式的值类别为右值
运算符地址的操作数必须是左值。右值不是左值。不能获取返回新值的表达式的地址
有点不清楚你想做什么。下面是一些表达式示例:
&(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
不是指针;这是一个数组。但是数组在使用该值的表达式中衰减为指向第一个元素的指针,因此在这种情况下,表达式的类型实际上是数组指针转换后的指针。@pmg您是说&(arr+1)
应该用C编译,还是说需要printf
用C打印东西?“如果我们保留第二个cout,则会产生编译错误。“-你是说报告的错误完全无法理解吗?在发布有关错误(尤其是编译错误)的问题时,请始终一字不差地发布错误消息,以及您认为错误消息的含义,或者您在理解错误消息中与代码相关的部分时遇到困难。您能否详细说明“arr不是指针”和“数组衰减为指针”?我一直认为数组是初始化多个顺序指针的一种方式。我错了吗?@BasinhetVeld我很确定你错了,尽管我甚至不太明白你所说的“初始化多个顺序指针”是什么意思。数组和指针是具有不同属性的不同事物。第一个是连续内存位置中的对象序列;后者是指向另一个对象的对象。数组指针衰减在许多情况下确实会使数组名称在许多情况下的行为与指针非常相似,因为转换后的数组实际上是指针。@errorika我的意思是(但不是很好)像:int*p=(arr+0)这样的指针;可以像arr变量-p[0]一样使用,(p+0)做同样的事情。但那正是因为腐烂。谢谢你的澄清注意
&(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