Monday, October 22, 2018

Dynamic memory allocation using calloc


Using calloc() function in C

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i, n;
    int *myspace;

    printf("Enter total numbers to be stored: ");
    scanf("%d", &n);
    
    /*Following statement will allot n blocks of int in memory.
      malloc returns a void pointer; then it is type-casted to (int*).
      myspace points to the first block of the newly allocated space.
    */
  myspace = (int*) calloc(n, sizeof(int)); 
    
    //It returns NULL pointer, if fails to allocate enough space.
    if(myspace == NULL) 
  {
        printf("Error!!! Space problem..");  exit(0);
    }
    //Logic to store numbers into the dynamically allocated space
    for(i=0; i<n; i++)
    {
       printf("Enter number %d:",i+1);
  scanf("%d", myspace+i);
    }
    //Logic to print numbers from dynamically allocated space
    printf("\n%d numbers stored into dynamically allotted space:\n", n);
  for(i=0; i<n; i++) 
  {
    printf("%d ", *(myspace+i));
    }
    return 0;
}


Output of Program

Enter total numbers to be stored: 5
Enter number 1:1
Enter number 2:3
Enter number 3:5
Enter number 4:7
Enter number 5:9

5 numbers stored into dynamically allotted space:
1 3 5 7 9

No comments:

Post a Comment