The malloc function is one of the functions in standard C to allocate memory. Upon successful allocation, malloc returns a void pointer (void *), which indicates that it is a pointer to a region of unknown data type. Here, we’ll use malloc() to dynamically assign memory from the HEAP to an array at runtime.
Language : C
[sourcecode language='c']
//Allocate memory dynamically to an array
#include
#include
void main()
{ int *a,c,n,i;
printf(“Enter size of array : “);
scanf(“%d”, &n);
a=(int *) malloc(sizeof(int));
for(i=0;i
printf(“Enter value of element %d :”, i+1);
scanf(“%d”, &c);
*(a+i)=c;
}
for(i=0;i
printf(“\n%d”,a[i]);
}
}
[/sourcecode]






