Sunday, September 26, 2010

Multidimensional Arrays in C, C++

C/C++ allows arrays of more than two dimensions. The exact limit, if any, is
determined by your compiler. The general form of a multidimensional array
declaration is
type name[Size1][Size2][Size3]. . .[SizeN];
Arrays of more than three dimensions are not often used because of the amount of
memory they require. For example, a four-dimensional character array with
dimensions 10,6,9,4 requires
10 * 6 * 9 * 4
or 2,160 bytes. If the array held 2-byte integers, 4,320 bytes would be needed. If the
array held doubles (assuming 8 bytes per double), 17,280 bytes would be required. The
storage required increases exponentially with the number of dimensions. For example,
if a fifth dimension of size 10 was added to the preceding array, then 172, 800 bytes
would be required.
In multidimensional arrays, it takes the computer time to compute each index. This
means that accessing an element in a multidimensional array can be slower than
accessing an element in a single-dimension array.
When passing multidimensional arrays into functions, you must declare all but the
leftmost dimension. For example, if you declare array m as
int m[4][3][6][5];
a function, func1() , that receives m, would look like this:
void func1(int d[][3][6][5])
{
.
.
.
}
Of course, you can include the first dimension if you like.

No comments:

Post a Comment