This blog is under construction

Monday, 30 April 2012

calloc example in C

Header file:

     void *calloc(size_t nmemb, size_t sz);

      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:

  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;

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

  Name: Jerry
  Age : 3

No comments:

Post a Comment