据我所知数组的地址a
是该数组的第一个元素的地址。
void func(int a[])
{
cout << "address in func: " << &a << endl;;
cout << "GT: " << &a[0] << endl;
}
int main ()
{
int a[] = {0,1,2,3};
cout << "address in main: " << &a << endl;
cout << "address in main a[0]: " << &a[0] << endl;
func(a);
}
Output:
address in main: 0x7ffef67d6790
address in main a[0]: 0x7ffef67d6790
address in func: 0x7ffef67d6778
GT: 0x7ffef67d6790
为什么是数组地址a
在 func() 中与地址的区别a[0]
?
为什么 func() 中数组 a 的地址与 a[0] 的地址不同?
因为你正在调用该函数func()
通过a
by value。这意味着a
函数内部func()
实际上是原件的副本decayed您要传递给的指针func()
from main()
。自从它们是不同的变量,它们有不同的地址。因此通过写cout << &a;
你正在打印这个单独的地址局部变数 named a
.
如果你想打印原来的地址,你应该在里面写func()
:
void func(int a[])
{
//---------------------------------v---------->removed the &
cout << "address in func: " << a << endl;;
cout << "GT: " << &a[0] << endl;
}
Demo https://onlinegdb.com/dgyYvxY1o
address in main: 0x7ffcfb0a4320
address in main a[0]: 0x7ffcfb0a4320
address in func: 0x7ffcfb0a4320
GT: 0x7ffcfb0a4320
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)