简体   繁体   中英

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

#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). 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[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. 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) . 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] . 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 . So &a[0] and a are equal.

q[0] is in fact p1 , q[1] is in fact p2 and q[2] is p3 .

Now p1 is the address of number so p1[0] is simply the value of number which you correctly computed to be 4.

p2 points to array so p2[1] is the same as array[1] which is the second element in array 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM