|Lessons||Lesson 24: Pointers and Multidimensional Arrays|
In the above statement, we have declared a 'char' type array of 5 rows and 10 columns.
A multi-dimensional array is stored in the memory in a series i.e. the elements of first row and first column and then the elements of the second row and coloumn and so on.
As discussed above, the array name points to the starting memory location of the memory allocated for the array elements. Here the question arises where the 'multi' will be pointing if we add 1 to ‘multi’. We know that a pointer is incremented by its type number of bytes. In this case, 'multi' is an array of 'char' type that takes 1 byte. Therefore, ‘muti+1’ should take us to the second element of the first row (row 0). But this time, it is behaving differently. It is pointing to the first element (col 0) of the second row (row 1). So by adding '1' in the array name, it has jumped the whole row or jumped over as many memory locations as number of columns in the array. The width of the columns depends upon the type of the data inside columns. Here, the data type is 'char', which is of 1 byte. As the number of columns for this array 'multi' is 10, it has jumped 10 bytes.
Remember, whenever some number is added in an array name, it will jump as many rows as the added number. If we want to go to the second row (row 1) and third column (col 2) using the same technique, it is given ahead but it is not as that straight forward.
Remember, if the array is to be accessed in random order, then the pointer approach may not be better than array indexing. We already know how to dereference array elements using indexing. So the element at second row and third column can be accessed as 'multi'. To do dereferencing using pointers we use '*' operator.
In case of one-dimensional array, '*multi' means 'the value at the address, pointed to by the name of the array'. But for twodimensional array '*multi' still contains an address of the first element of the first row of the array or starting address of the array 'multi'.
See the code snippet to prove it.
/* This program uses the multi-dimensional array name as pointer */
Now, look at the output below:
The value of multi
It is pertinent to note that in the above code, the array ‘multi’ has been changed to ‘int’ from ‘char’ type to avoid any confusion.
To access the elements of the two-dimensional array, we do double dereferencing like '**multi'. If we want to go to, say, 4th row (row 3), it is achieved as 'multi + 3' . Once reached in the desired row, we can dereference to go to the desired column. Let's say we want to go to the 4th column. It can be done in the following manner.
NEXT>>>>>Lesson 25. Pointers to Pointers