[英]Multi dimensional array and pointer in c++
int a[2][2] = {{1, 2}, {3, 4}};
cout << a << endl;
cout << *a << endl;
cout << &a[0][0] << endl;
The output of this code is:这段代码的输出是:
0x7fff3da96f40
0x7fff3da96f40
0x7fff3da96f40
However, if a
is 0x7fff3da96f40
then *a
should be the value in the address 0x7fff3da96f40
which is 1
.但是,如果a
是0x7fff3da96f40
那么*a
应该是地址0x7fff3da96f40
的值,即1
。
But, we get the same address again.但是,我们又得到了相同的地址。
Why is this happening?为什么会这样?
*a
should be the value in the address0x7fff3da96f40
*a
应该是地址0x7fff3da96f40
的值
It is.这是。 The key is what type the value has, and that type is int[2]
.关键是值具有什么类型,该类型是int[2]
。
cout
can't print arrays directly, but it can print pointers, so your array was implicitly converted to a pointer to its first element, and printed as such. cout
不能直接打印数组,但它可以打印指针,因此您的数组被隐式转换为指向其第一个元素的指针,并按原样打印。
Most uses of arrays do this conversion, including applying *
and []
to an array.数组的大多数用途都会进行这种转换,包括将*
和[]
应用于数组。
If you try如果你试试
int a[2][2] = {{1, 2}, {3, 4}};
cout << a << endl;
cout << *a << endl;
cout << &a[0][0] << endl;
cout << typeid(a).name() << endl;
cout << typeid(*a).name() << endl;
cout << typeid(&a[0][0]).name() << endl;
the possible output is可能的输出是
0x7ffe4169bb50
0x7ffe4169bb50
0x7ffe4169bb50
A2_A2_i
A2_i
Pi
So now you can see what types are the variables you are using.所以现在你可以看到你正在使用的变量是什么类型。 They are somewhat different entities, starting on same memory address.它们是有些不同的实体,从相同的内存地址开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.