[英]Multidimensional array
The question is to find the output of the follwing program. 问题是要找到以下程序的输出。 This came out in my test and i got wrong. 这是在我的测试中得出的,我错了。 My answer was 4, 7, 10. The answer is 4,8,12 but i need an explanation on how it works 我的答案是4、7、10。答案是4、8、12,但我需要对其工作方式进行解释
#include<iostream>
using namespace std;
int main ()
{
int number = 4;
int array[] = {7,8,9,10,11,12,13};
int *p1 = &number ;
int *p2 = array;
int *p3 = &array[3];
int *q[] = {p1,p2,p3};
cout << q[0][0] << endl ;
cout << q[1][1] << endl ;
cout << q[2][2] << endl ;
return 0;
}
What you have is not a multi-dimensional array (C++ doesn't really have it). 您拥有的不是多维数组(C ++确实没有)。 What you have is an array of pointers. 您拥有的是一个指针数组。 And pointers can be indexed like arrays. 指针可以像数组一样被索引。
In "graphic" form the array q
looks something like this: 以“图形”形式,数组q
看起来像这样:
+------+------+------+ | q[0] | q[1] | q[2] | +------+------+------+ | | | v | v +------+ | +-----+----------+----------+-----+ |number| | | ... | array[3] | array[4] | ... | +------+ | +-----+----------+----------+-----+ v +----------+----------+-----+ | array[0] | array[1] | ... | +----------+----------+-----+
Some notes: 一些注意事项:
What most people call multidimensional arrays are actually arrays of arrays. 大多数人所说的多维数组实际上是数组的数组。 Much like you can have an array of integers, or like in the case of q
in your code an array of pointers to integers, one can also have an array of arrays of integers. 就像您可以拥有一个整数数组,或者就像在代码中q
的情况下,是一个指向整数的指针数组一样,也可以拥有一个整数数组数组。 For more "dimensions" it's just another nesting of arrays. 对于更多的“维度”,它只是数组的另一个嵌套。
As for why pointers and arrays both can be indexed the same way, it's because for any array or pointer a
and (valid) index i
, the expressions a[i]
is equal to *(a + i)
. 至于为什么指针和数组都可以以相同的方式进行索引的原因,这是因为对于任何数组或指针a
和(有效)索引i
,表达式a[i]
等于*(a + i)
。 This equality is also the reason you can use an array as a pointer to its first element. 这种相等性也是您可以将数组用作指向其第一个元素的指针的原因。 To get a pointer to an arrays first element one can write &a[0]
. 要获得指向数组的指针,第一个元素可以写&a[0]
。 It's equal to &*(a + 0)
, where the address-of and dereference operators cancel each other out leading to (a + 0)
which is the same as (a)
which is the same as a
. 它等于&*(a + 0)
,其中地址运算符和取消引用运算符相互抵消,导致(a + 0)
与(a)
相同,而a
与相同。 So &a[0]
and a
are equal. 因此&a[0]
和a
相等。
q[0]
is in fact p1
, q[1]
is in fact p2
and q[2] is p3
. q[0]
实际上是p1
, q[1]
实际上是p2
,q [2]是p3
。
Now p1 is the address of number
so p1[0] is simply the value of number which you correctly computed to be 4. 现在p1为的地址number
,以便P1 [0]是你正确地计算为4号的简单值。
p2
points to array so p2[1] is the same as array[1] which is the second element in array ot 8
. p2
指向数组,因此p2 [1]与array [1]相同,后者是数组ot 8
的第二个元素。
p3
points to the subarray of array
starting from position 3. So p3[2]
is the same as array[3 + 2] = array[5]
= 12. p3
指向从位置3开始的array
的子array
。因此p3[2]
与array[3 + 2] = array[5]
= 12相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.