This blog is under construction

Monday 30 April 2012

calloc example in C

Header file:
    stdlib.h

Synopsis:
     void *calloc(size_t nmemb, size_t sz);

Description:
      It dynamically allocates memory and returns pointer to the allocated space for an array of nmemb objects, each of size sz.  And the allocated memory is initialized to 0.  It returns NULL on error.


calloc function C example:


  #include<stdio.h>
  #include<stdlib.h>
  #include<string.h>
  struct db {
        char name[50];
        int age;
  };

  int main() {
        struct db *calloc_data;
        /* dynamic memory allocation using calloc */
        calloc_data = (struct db*)calloc(2, sizeof (struct db));

        /* initialization */
        strcpy(calloc_data[0].name, "Tom");
        calloc_data[0].age = 2;
        strcpy(calloc_data[1].name, "Jerry");
        calloc_data[1].age = 3;

        /* printing output */
        printf("Name: %s\n", calloc_data[0].name);
        printf("Age : %d\n\n", calloc_data[0].age);
        printf("Name: %s\n", calloc_data[1].name);
        printf("Age : %d\n\n", calloc_data[1].age);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Name: Tom
  Age : 2

  Name: Jerry
  Age : 3


No comments:

Post a Comment