Showing posts with label Multi-Dimensional Arrays. Show all posts
Showing posts with label Multi-Dimensional Arrays. Show all posts

Thursday, March 10, 2016

Accessing and Initialization of Two Dimensional Array

The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is essentially, an array of one-dimensional arrays. To declare a two-dimensional integer array "S" of size 10,20, you would write.
int s[10][20];
Two-dimensional arrays are stored in a row-column matrix, where the first index indicates the row and the second indicates the column. This means that the rightmost index changes more quickly than the leftmost when accessing the elements in the array in the order in which they are actually stored in memory.

Suppose, you want to access element located at 3'rd row and 5'th column of the two dimensional array "S", store the value in a integer variable var then the statement would be like this :
int var =  s[2][4]; /* As Array index start from 0, 2 indicates 3'rd Row and 4 indicates 5'th Column*/

Wednesday, March 9, 2016

Multi-Dimensional Arrays

 C language also supports multi dimensional arrays. The number of maximum dimension you can use in your program is delimited by your compiler. The generic form of declaring a multi dimensional array is:
 [Size1][Size2][Size3]. . .[SizeN];

Elements of Multi-Dimensional Arrays

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,9,8,7 requires 10 * 9 * 8 * 7 or 5040 bytes.
If it is an integer array, then it would take 4 times the memory. So you can imagine that how big the memory becomes.
In multidimensional arrays, computer takes more 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-dimensional array.
It is good to have a look at how the elements in multidimensional array stored in memory. For simplicity, take a three dimensional array. As you can see earlier, arrays are stored in continuous way in memory. For a three dimensional array, you can imagine the memory allocation like a Rubik’s cube. Memories are allocated from 1'st row followed by 2'nd level and so on. In this way memories are allocated one after another.