[英]What's the type difference between a, &a, and &a[0]?
#include <iostream>
void arrayFunctionA(int* p)
{
}
int main()
{
int a[3] = {7, 7, 7};
arrayFunctionA(a);
arrayFunctionA(&a[0]);
arrayFunctionA(&a);
return 0;
}
This will not compile, with an error on arrayFunctionA(&a);
这将无法编译,并且在
arrayFunctionA(&a);
上arrayFunctionA(&a);
错误arrayFunctionA(&a);
. 。
So, a
and &a[0]
evaluates as int*
, but &a
does not. 因此,
a
和&a[0]
计算结果为int*
,而&a
则不。
What is the distinction between these 3? 这3个有什么区别?
a
is an array of 3 int
type ( int [3]
). a
是3个int
类型的数组( int [3]
)。
A fixed array decays to a pointer to its first element, so in arrayFunctionA(a)
, a
will decay into an int*
pointer to it's first element. 固定数组会衰减为其第一个元素的指针,因此在
arrayFunctionA(a)
, a
将衰减为指向其第一个元素的int*
指针。
&a[0]
is the address of the array's first element, and is of type int *
. &a[0]
是数组第一个元素的地址,类型为int *
。
&a
is the address of the array itself, and is of type int (*)[3]
(pointer to an array of 3 int
). &a
是数组本身的地址,类型为int (*)[3]
(指向3 int
数组的指针)。
So, for a function with signature 因此,对于具有签名的功能
void arrayFunctionA(int* p);
Passing a
or &a[0]
will serve the same purpose, while passing &a
will result in an incompatibility between the passed argument value and the function parameter. 传递
a
或&a[0]
会达到相同的目的,而传递&a
会导致传递的参数值和函数参数之间不兼容。
The first two examples are identical. 前两个示例相同。
a
decays to a pointer and binds to the int*
taken by the function. a
衰变到一个指针和结合于int*
采取的功能。 &a[0]
is identical to &*(p + 0)
which yields a int*
. &a[0]
等于&*(p + 0)
,它产生一个int*
。 The third example doesn't compile because applying the address-of operator ( &
) to an array yield a pointer to an array. 第三个示例未编译,因为将地址运算符(
&
)应用于数组会产生指向数组的指针。 In your example the result is a int(*arr)[3]
which cannot bind to a int*
so you get the compilation error. 在您的示例中,结果是无法绑定到
int*
的int(*arr)[3]
,因此会出现编译错误。
Оn the first call arrayFunctionA(a);
arrayFunctionA(a);
第一次调用arrayFunctionA(a);
the actual address of a
is being passed. 实际地址
a
被传递。
Оn the second call arrayFunctionA(&a[0]);
arrayFunctionA(&a[0]);
第二个调用arrayFunctionA(&a[0]);
the actual address of index 0 is being passed. 索引0的实际地址正在传递。
The first and second calls are identical. 第一次和第二次通话是相同的。 You both get the address of index 0 (remember that an array is also a pointer).
你们都得到索引0的地址(记住数组也是指针)。
On the third call you are getting the pointer of a
which is already a pointer. 在第三个电话你得到的指针
a
它已经是一个指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.