C program to implement multi dimensional arrays using pointers

      Memory allocation in case of multi dimensional arrays is done with help of pointer to pointer concept. Initially memory for single array will be allocated where each element of an array is a pointer. That every element which is a pointer stores the address of newly created array which can hold more values. In this way using the pointer to pointer concept memory for multi dimensional arrays will be allocated. This program allocates the memory required for elements in a matrix and moreover it displays contents of a matrix after reading values from the user. Thus, the program demonstrates multi dimensional arrays using pointers.

C program to implement multi dimensional arrays using pointers



Source Code :

#include<stdio.h>
#include<stdlib.h>
#define ROW 5
#define COL 5
int main()
{
	int **arr,i,j;                          //Step 1
	arr=(int **)malloc(ROW*sizeof(int *));  //Step 2
	if(!arr)
	{
	     printf("out of memory\n");
	     exit(EXIT_FAILURE);
	}
	for(i=0;i < ROW;i++)
	{
		arr[i]=(int *)malloc(sizeof(int)*COL); //Step 3
		if(!arr[i])
		{
		     printf("out of memory\n");
		     exit(EXIT_FAILURE);
		}
	}
	printf("\n Enter the Elements of the matrix row by row : \n");
	for(i=0;i < ROW;++i)
	for(j=0;j < COL;++j)
	scanf("%d",&arr[i][j]);       //Step 4
	printf("\n The matrix Is as follows...\n");
	   for(i=0;i < ROW;++i)
	     {
		printf("\n");
		for(j=0;j < COL;++j)
		printf("%d\t",arr[i][j]);   //Step 5
	     }
return 0;
}


edit-code-image

Sample Test cases :

1.  Enter the Elements of the matrix row by row :
               1 2 3 4 5
               2 3 4 5 6
               3 4 5 6 7
               4 5 6 7 8
               5 6 7 8 9

    The matrix Is as follows...

       1       2       3       4       5
       2       3       4       5       6
       3       4       5       6       7
       4       5       6       7       8
       5       6       7       8       9

Explanation:

Step 1: In order to dynamically allocate the memory for multi dimensional arrays, the pointer to pointer variable **arr is decalred.

Step 2: This step allocates the memory required for rows and returns pointer to pointer for the corresponding memory address.

Step 3: This step allocates the memory required for columns which stores the returned address in the arr[i].

Step 4: Now the elements are read from the user using scanf() function.

Step 5: The contents of a matrix are displayed on the output screen using printf() function.

More Insights:

1. More about DMA.

1. Pointer to pointer concept.

Explore C Programs:C Programs