Dynamic Memory Allocation Lecture 21
Dynamic Memory Allocation Lecture 21
int *p,n,i;
printf("Enter the number of blocks we want to reserve:") ;
scanf("%d",&n) ;
p=(int*)calloc(n,sizeof(int));//malloc() returns void* so we need to typecast with the specific data type
if(p==NULL)
{
printf("Memory not available\n");
exit(1);
}
else
{
printf("\n Memory allocation successful");
printf ("\nEnter integer values: ") ;
for(i=0;i<n;i++)
{
scanf("%d",p+i);
}
printf("\n Entered values are:");
for(i=0;i<n;i++)
printf("\n%d",*(p+i));
return 0;
©LPU}CSE101 C Programming
Difference between malloc() and calloc()
calloc() malloc()
Function: Allocates a region of memory Allocates "size" bytes of
large enough to hold "n memory.
elements" of "size" bytes each.
Return value: void pointer (void *). void pointer (void *).
If the allocation succeeds, a If the allocation succeeds, a
pointer to the block of memory pointer to the block of memory
is returned. is returned.