C program that demonstrates dynamic memory allocation in 2D arrays

      Dynamic memory allocation in 2D arrays in C programming is possible with help of special library functions available in “stdlib.h”. Those are malloc(), calloc() and realloc(). This program allocates the memory for all elements in a matrix with help of single pointer. Later that pointer is incremented while assigining the values until all values are read.

dynamic memory allocation in 2D arrays



Source Code :

#include<stdio.h>
#include<stdlib.h>
void getdata(int *,int, int);
void showdata(int *,int,int);
int main()
{
	int row, col;
	int *a;
	printf("\n ENTER THE NUMBER OF ROWS:");
	scanf("%d",&row);                        //Step 1
	printf("\n ENTER THE NUMBER OF COLUMNS:");
	scanf("%d",&col);                        //Step 1
	a=(int *)malloc(row*col*sizeof(int));    //Step 2
	getdata(a,row,col);                      //Step 3
	showdata(a,row,col);                     //Step 4
	free(a);
	a=NULL;
	return 0;
}
void getdata(int *p,int r, int c)
{
	int i,j;
	printf("\n Enter the Numbers one by one....\n");
	for(i=0;i < r;++i)
		for(j=0;j < c;++j)
		{
		     scanf("%d",p);
		      p++;                     //Step3(i)
		}
}
void showdata(int *p,int r,int c)
{
	int i,j;
	printf("\n The MATRIX is as follows....\n");
	for(i=0;i < r;++i)
	{
	     printf("\n");
	     for(j=0;j < c;++j)
	       {
		 printf("\t %d",*p);
		 p++;
	       }
	}
}


edit-code-image

Sample Test cases:

1.  ENTER THE NUMBER OF ROWS      :2
    ENTER THE NUMBER OF COLUMNS   :2
    Enter the Numbers one by one....
                                   4
                                   8
                                   3
                                   6

   The MATRIX is as follows....
         4       8
         3       6

2. 
    ENTER THE NUMBER OF ROWS     :1
    ENTER THE NUMBER OF COLUMNS  :1
    Enter the Numbers one by one....
                                  45

   The MATRIX is as follows....
         45

Explanation:

Step 1 : The number of rows and the number of columns in a matrix are read from the user using the scanf() function.

Step 2 : Memory gets allocated using malloc() function that is sufficient for total number of elements in the matrix.

Step 3 : The function getdata(int *p,int r,int c) is called from the main program which reads values from the user into the matrix.

Step 3(i): The pointer gets incremented because it has to store the address of next element.

Step 4 : Finally, The function showdata() displays the contents of a matrix.

More Insights:

1. More about DMA.

More Content : ToPoint
More about C Programming: C Programming