# Multidimensional arrays

• 03-25-2011
Dontgiveup
Hallo, I am trying to understand how multidimensional arrays work but can't seem to figure it out. I would like help in understanding them. Yeah googled already but what I have seen so far seem to say "a multidimensional is an array of an array" which doesn't help much in understanding. I have a code here and its output. I would like someone to explain it to me the outcome well. Thanks in advance.

Code:

```#include <iostream> using namespace std; intmain() { intar[]={123,456,789}; intind[]={2,1,2,0}; intk; for (k=0;k<4;k=k+1) { cout<< ar[ind[k]]; } return 0; }```
Output: 789456789123

OK I think I figure it out.

OK the loop produces the values 0, 1, 2 and 3. Putting this in the array the statement becomes:

cout<< ar[ind[0]]; and so on till array 3.

From here then it is easier. Because ind[0] = 2, so it becomes array[2]. Although I understand this but intar[] has only 3 values while ind has 4, so when intar runs out of values to loop over, what is supposed to happen? Does it go back to zero and start it all over again or?
• 03-25-2011
Mr.777
First, these are not multidimensional arrays but only single arrays.
Quote:

when intar runs out of values to loop over, what is supposed to happen?
Definiterly, crash..... Boooooooooommmmmmmm!!!
No it will not go back to zero, a runtime error.
• 03-25-2011
Elysia
Erm, nothing of the sort.
It doesn't matter that ind has more indices than array. The simple reason is that ind stores the indices in array that you're going to access. So ind can be of infinite length and it will all be well so long as the contents of ind is 0 < i < length of array - 1.
• 03-25-2011
Dontgiveup
Thank you Elysia and Mr.777. I now understood it. So you basically output the values in ar[0],ar[1],ar[2],and finally again ar[0]. Ooh and I thought it was a multidimensional array.
• 03-25-2011
C_ntua
Quote:

Originally Posted by Dontgiveup
Thank you Elysia and Mr.777. I now understood it. So you basically output the values in ar[0],ar[1],ar[2],and finally again ar[0]. Ooh and I thought it was a multidimensional array.

It actually outputs ar[2], ar[1], ar[2], ar[0] as you can see from the result.

You can always take it step by step and figure it out.
1st loop: k=0
ar[ind[k]] = ar[ind[0]]
you know that ind[0] = 2
ar[ind[0]] = ar[2]
you know that ar[2] = 789 thus
ar[ind[k]] = 789
which is what you get

2nd loop: k=1
etc etc