C++ Learning Resource Network!

 C++ Tutorials  >  Arrays  >  Two Dimensional Arrays
The arrays we have so far used have been one-dimensional, that is, they could be represented as a single row or a column(refer Figure 4.2 and 4.3).
C A T H Y \0

Figure 4.2 Array Represented as a Single Row


Figure 4.3 Array Represented as a Single Column

A typical two-dimensional array is like a time-table. To locate a piece of inforamtion, you determine the required row and column and then read the location where they meet. In the same way, a two dimensional array is a grid containing rows and columns in which each element is uniquely specified by means of its row and column coordinates. Two-dimensional character arrays hold an array of strings wherein a row represents a string and a column represents a single character in each of the strings.


The general form of declaration of a two-dimensional character array is:

char arrayname[x][y];

where 'x' is the number of rows and 'y' is the number of columns.

The following guidelines need to be followed while declaring two-dimensional character arrays.

> The number of rows should be equal to the number of strings in the array.

> Column specification should be greater than or equal to the length of the longest string in the array plus one.

For example, if there are seven strings in an array and the length of the longest string is nine, the array can be declared in the following manner:

char cWeekdays[7][10];

Initializing Two-dimensional Arrays

The rules for initializing two-dimensional arrays are the same as for one-dimensional arrays.

For example, to declare and initialize an array that would hold the days of the week, the array definition would be:

char cWeekdays[7][10] = {


In the above example, cWeekdays[0] will refer to the string "Sunday" and cWeekdays[4][1] would refer to the character 'h' of the string "Thursday". Consider the following program, which accepts values into a two-dimensional character array and displays them.


| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.