- The typical array in the C language
is simply a series of variables.
All of the same type marching off together.
But not every type of data is a single line.
Sometimes you have to deal with a grid.
In that case, you enter into the realm
of the multidimensional array.
This movie uncovers the mystery
of the multidimensional array.
You'll learn how to configure such an array,
and access its values.
You'll also see how multidimensional arrays
apply to strings.
To visualize a multidimensional array, think of a grid.
You have rows and columns.
The array is declared at line 8.
Two sets of square brackets are used.
One for each dimension in the array.
So grid is an integer array.
It's effectively a two-dimensional array.
Lines 12-14 use a nested loop to fill each array
element with a value 0, initializing the array.
In line 14, you see that individual array elements
require two square brackets as reference.
Again, think of each as rows and columns.
Then the nested loops starting at line 17 print the array
in rows and columns.
Build and run the code.
The output shows each array element
as it would be referenced.
So the first one is element 0,0.
That's the first element in both directions.
As a thought experiment, how would you modify the code
to set the value of the third element
in both dimensions to the value 1.
Would you change it here, or here.
I hope you remember that arrays start with element 0.
So the third element is actually referenced as grid 2,2.
We're going to add a line that reads grid[2][2] = 1;
Save that change.
Build and run.
This is how the value looks.
With a value 1 at grid 2.2.
If you put a 1 here, you're actually using
the fourth element in both dimensions.
That's wrong.
Because you have to remember that all arrays start
with element 0, not element 1.
Even the pros forget that from time to time.
And when you're dealing with two dimensions,
it gets even worse.
You can also conjure up a two-dimensional character array,
as is shown in exercise multi2.
A two dimensional character array is simply
a collection of strings, but with one important caveat.
The array must be dimensioned to handle the largest string.
Remember, a two-dimensional array is a grid.
Here the longest string is six letters long,
plus one element for the NULL character.
That makes seven elements for each string.
And when printing strings from a two-dimensional
character array, you need only specify the first dimension.
Which is done on line 14.
Build and run the code.
The C language also offers three-dimensional arrays.
And even more dimensions than that.
When you create such an array,
you need one set of brackets for each dimension.
And things can get pretty complex in a hurry.
For now, concentrate on playing with two-dimensional arrays.
As a thought, whether you believe it or not,
if you've been taking this course from the beginning,
you have everything you need to know to program
a rudimentary Tic-tac-toe computer game.
Give it a try.