![]() |
| Dynamic Array in C |
Dynamic Array:-
The memory allocated by malloc( ), calloc( ) and realloc( ) is always made of contiguous bytes. Moreover in C there may be an equivalence between pointer notation and subscript notation i.E. We are able to observes subscripts to a pointer variable. So we are able to get right of entry to the dynamically allotted reminiscence thru subscript notation also. We can utilize these functions to 'create dynamic arrays whose size can range at some point of run time. Now we'll write the program the use of subscript notation.
/* Program to access to dynamically allocated memory in 1-D Array */
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p,n,i;
printf("Enter the number of integer") ;
scanf("%d" ,&n) ;
p=(int *)malloc(n*sizeof(int));
if(p==NULL)
{
printf ("Memory not available\n");
exit(1);
}
for(i=0;i<n;i++)
{
printf ("Enter an integer ") ;
scanf("%d",&p[i]) ;
}
for(i=0;i<n;i++)
printf("%d\t",p[i]);
return 0;
}
In this way we can simulate a I-D array for which 'size' is entered at execution time.
______________________________________
/* Program to access to dynamically allocated memory in 2-D Array */
#include<stdio.h>
#include<stdlib.h>
int main( )
{
int i,j,rows;
int (*a)[4];
printf("Enter number of rows:");
scanf("%d",&rows);
a=(int(*)[4])malloc(rows*4*sizeof(int));
for(i=0;i<rows;i++)
for(j=0;j<4;j++)
{
printf("Enter a[%d][%d]",i,j);
scanf ("%d",&a[i][j]);
}
printf ("The matrix is : \n");
for(i=0;i<rows;i++)
{
for(j=0;j<4;j++)
printf("%5d",a[i][j]);
printf("\n");
}
free(a);
return 0;
}
_______________________________________
Conclusion:
In short an arrays, which size is declared during run time with help of malloc() or calloc() function such type array is know as dynamic array in C.
