1D/2D Arrays


Richard Marks:
1D/2D Arrays

I've been explaining the logic behind using single dimension arrays for implementing 2D arrays easily for years.
I'm tired of doing it, so I'm writing it here for once and for all. 8)

Ok, visualize a hand of playing cards.
if you place them in front of you in a row, lets say that its a simple set of ace,two,three,four,five,six,seven,eight
Here we have our 8 cards:



to represent this as an array, we can do:


char cards[] = {'A','2','3','4','5','6','7','8'};

if we want to arrange the cards in 2 rows of four cards:



then, we can use a 2 dimensional array like this:


char cards[2][4] = {{'A','2','3','4'},{'5','6','7','8'}};

but thats ugly to init..

so lets use a one dimensional array:

char cards[] = {'A','2','3','4','5','6','7','8'};

hey that looks the same as before! (yep)
but how do we tell which cards go on which row?
easy. we just need to use the equation p=x+y*w

the position of the [5] card should be on the second row, in the first column.
so X = 0 and Y = 1
pump that into our equation. i = 0+1*4 ..that gives us 4
cards[4] is in fact the [5] card that we expect!

I hope that this helps clear things up.
Let me know if you have questions.


[0] Message Index