C: More Operators and Arrays - Two-Dimensional Arrays
(Page 4 of 5 )
Like most programming languages, C allows you to create two-dimensional and multi-dimensional arrays. A two-dimensional array works like a grid, or a spreadsheet, creating rows and columns to store data in. In the example below, the first number represents the number of rows, while the second number represents the number of columns:
char name[2] [4];
This creates a two-dimensional array with two rows and four columns. If we wanted to assign values to our array, we could do this:
char name[2] [4] = {{'B','i','l','l'},
{'D','i','n','g'}};
This creates an array that contains the name Bill Ding. If I wanted to create two variables to hold the initials of Mr. Bill Ding, I could do so like this:
char firstInitial;
firstInitial = name[0][0];
char lastInitial;
lastInitial = name[1][0];
Remember that arrays start at 0, so row 0, column 0 would equal "B" and row 1, column 0 would equal "D". We could also change a value in the array. Let's say we wanted to change the name to Bill Dung. We would have to access the "i" in Ding to do so:
name[1] [1] = 'u';
Note that the "i" in Ding is located in the second row and the second column. The n is located in the second row, third column, etc.
Also note that we don't always need to set the size of an array, but it is good practice to do so.
And finally, we can also set the values of a multidimensional array like this:
char name[2] [4];
name [0] [0] = 'B';
name [0] [1] = 'i';
name [0] [2] = 'l;
name [0] [3] = 'l';
name [1] [0] = 'D';
name [1] [1] = 'i';
name [1] [2] = 'n';
name [1] [3] = 'g';
There are also ways to Loop through arrays and ways to create dimensional arrays larger than two dimensions, but those are beyond our scope (we will cover looping through arrays in a future article, however, when we discuss loops).
Next: Commenting on Your Code >>
More BrainDump Articles
More By James Payne