Two dimensional array implementation using pointers
C Program to access a two dimensional array using pointer
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void print_matrix(int mat[MAX][MAX], int rows, int cols);
void input_matrix(int mat[MAX][MAX], int rows, int cols);
void main()
{
int mat[MAX][MAX];
int rows, cols;
printf("Enter the number of rows in the matrix\t:");
scanf("%d",&rows);
printf("Enter the number of columns in the matrix\t:");
scanf("%d",&cols);
printf("\nEnter elements in the matrix\n");
input_matrix(mat, rows, cols);
printf("\nElements of the matrix are\n");
print_matrix(mat, rows, cols);
getch();
}
void input_matrix(int mat[MAX][MAX], int rows, int cols)
{
int i, j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
scanf("%d",(*(mat+i)+j));
}
}
}
void print_matrix(int mat[MAX][MAX], int rows, int cols)
{
int i, j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf("%d ",*(*(mat+i)+j));
}
printf("\n");
}
}
Output
Enter the number of rows in the matrix :3
Enter the number of columns in the matrix :3
Enter elements in the matrix
1
2
3
4
5
6
7
8
9
Elements of the matrix are
1 2 3
4 5 6
7 8 9
Explanation
Let us suppose a two - dimensional array
For the above array, elements representation is:
mat[0][0] mat[0][1] mat[0][2]
mat[1][0] mat[1][1] mat[1][2]
mat[2][0] mat[2][1] mat[2][2]
For the above array,
So, in general, *(*(mat + i) + j) points to mat[i][j].
For scanf, (*(mat + i) + j) is used and for printf, *(*(mat + i) + j) is used.
int mat[3][3];
For the above array, elements representation is:
mat[0][0] mat[0][1] mat[0][2]
mat[1][0] mat[1][1] mat[1][2]
mat[2][0] mat[2][1] mat[2][2]
For the above array,
mat |
=> | Points to base address of two-dimensional array. Since array decays to pointer. |
|
||
*(mat) |
=> | Points to first row of two-dimensional array. |
*(mat + 0) |
=> | Points to first row of two-dimensional array. |
*(mat + 1) |
=> | Points to second row of two-dimensional array. |
*(mat + 2) |
=> | Points to third row of two-dimensional array. |
|
||
**mat |
=> | Points to mat[0][0] |
*(*(mat + 0)) |
=> | Points to mat[0][0] |
*(*(mat + 0) + 0) |
=> | Points to mat[0][0] |
*(*mat + 1) |
=> | Points to mat[0][1] |
*(*(mat + 0) + 1) |
=> | Points to mat[0][1] |
*(*(mat + 0) + 2) |
=> | Points to mat[0][2] |
So, in general, *(*(mat + i) + j) points to mat[i][j].
For scanf, (*(mat + i) + j) is used and for printf, *(*(mat + i) + j) is used.