as

Thursday 13 November 2014

Dynamic Memory Allocation using Pointers


Arrays occupy fixed size of memory. If you declare array to store 100 integer values, total memory reserved by system is 200 bytes (100*2).

But what if we need to store only 20 integer values? At runtime, we can not resize array.
That's when dynamic memory allocation concept comes into picture. With dynamic memory mechanism, we can reserve only enough memory that is required. So we can save memory if we use dynamic memory allocation.

C provides 4 important functions that can be used to work with dynamic memory allocation.
  1. malloc
  2. calloc
  3. realloc
  4. free

  1. Below example will clarify how to handle dynamic memory in C.

#include <stdio.h>
#include <stdlib.h>
int main()
{

  //int * p = malloc(10*sizeof(int));
  int * p = calloc(10, sizeof(int));
  //both statements
 
  if (p==NULL)
  {
    printf("unable to allocate 20 bytes");
    exit(1);
   }
  int i;
for(i=0;i<10;i++)
  *(p+i) = i;
for(i=0;i<10;i++)
printf("%d ",   *(p+i) );


p = realloc(p,20*sizeof(int));
for(i=10;i<20;i++)
  *(p+i) = i;

for(i=0;i<20;i++)
printf("%d ",   *(p+i) );

free(p);

}








No comments:

Post a Comment

Leave your valuable feedback. Your thoughts do matter to us.

Sponsored Links

Popular Posts

Comments

ShareThis