Tutorial - Multidimensional Arrays - Part 2
Tutorial
Compiled from multiple sources from the internet. For practice kindly use the IDE.
Multidimensional Arrays Tutorial - Part 2
Pointers and 2D Arrays
As we know that the one dimensional array name works as a pointer to the base element (first element) of the array. However in the case 2D arrays the logic is slightly different. You can consider a 2D array as collection of several one dimensional arrays.
So abc[0] would have the address of first element of the first row (if we consider the above diagram number 1).Similarly abc[1] would have the address of the first element of the second row.
Example:
#include <stdio.h>
int main()
{
int abc[5][4] ={
{0,1,2,3},
{4,5,6,7},
{8,9,10,11},
{12,13,14,15},
{16,17,18,19}
};
for (int i=0; i<=4; i++)
{
/* The correct way of displaying an address would be
* printf("%p ",abc[i]); but for the demonstration
* purpose I am displaying the address in int so that
* you can relate the output with the diagram above that
* shows how many bytes an int element uses and how they
* are stored in contiguous memory locations.
*
*/
printf("%d ",abc[i]);
}
return 0;
}
Output:
1600201376 1600201392 1600201408 1600201424 1600201440
The actual address representation should be in hex for which we use %p instead of %d, as mentioned in the comments. This is just to show that the elements are stored in contiguous memory locations. You can relate the output with the diagram above to see that the difference between these addresses is actually number of bytes consumed by the elements of that row.
The addresses shown in the output belongs to the first element of each row abc[0][0], abc[1][0], abc[2][0], abc[3][0] and abc[4][0].
Try getting and printing user inputs for 2D arrays using pointers using the IDE.
Practice Exercises:
- To subtract two matrices.
- To perform Scalar matrix multiplication.
- To multiply two matrices.
- To check whether two matrices are equal or not.
- To find sum of main diagonal elements of a matrix.
- To find sum of minor diagonal elements of a matrix.
- To find sum of each row and column of a matrix.
- To interchange diagonals of a matrix.
- To find upper triangular matrix.
- To find lower triangular matrix.
- To find sum of upper triangular matrix.
- To find sum of lower triangular matrix.
- To find transpose of a matrix.
- To find determinant of a matrix.
- To check Identity matrix.
- To check Sparse matrix.
- To check Symmetric matrix.
- To add two matrices.
Comments