We use the calloc function to allocate memory at run time for derived data types, such as arrays and structures.
Using the calloc function, we can allocate multiple memory blocks of the same size, and all bytes will be set to 0.
This is different from the malloc function used to allocate a single memory space in the previous tutorial.
The following is the syntax of the 'calloc' function, which is used to dynamically allocate memory.
ptr = (cast_type *) calloc (n, element_size);
Where, "ptr" is a pointer of type" cast_type".
n is the total block of contiguous Spaces, each of size element_size, which will be allocated using the calloc function.
In the following example, we allocate memory space for three student structure variables.
//student structure
struct student {
char id[10];
char firstname[64];
char lastname[64];
int score;
};
//new type
typedef struct student candidate;
//student structure pointer
candidate *sptr;
//variables
int no_of_students = 3;
//allocate memory blocks
sptr = (candidate *) calloc (no_of_students, sizeof(candidate));
In the above code, we have allocated three storage space blocks
| member | data type | size |
|---|---|---|
| id | char | 10 bytes |
| firstname | char | 64 bytes |
| lastname | char | 64 bytes |
| score | int | 2 bytes |
#include <stdio.h>
#include <stdlib.h>
int main(void) {
//student structure
struct student {
char id[10];
char firstname[64];
char lastname[64];
int score;
};
//new type
typedef struct student candidate;
//student structure pointer
candidate *sptr;
candidate *tmp;
//variables
int no_of_students = 3;
int i;
//allocate memory blocks
sptr = (candidate *) calloc (no_of_students, sizeof(candidate));
//get student details
for(i = 0, tmp = sptr; i < no_of_students; i++, tmp++) {
printf("Enter detail of student #%d\n", (i+1));
printf("ID: ");
scanf("%s", tmp->id);
printf("First Name: ");
scanf("%s", tmp->firstname);
printf("Last Name: ");
scanf("%s", tmp->lastname);
printf("Score: ");
scanf("%d", &tmp->score);
}
//display student details
printf("\n\nFollowing are the student details:\n\n");
for(i = 0, tmp = sptr; i < no_of_students; i++, tmp++) {
printf("Detail of student #%d\n", (i+1));
printf("ID: %s\n", tmp->id);
printf("First Name: %s\n", tmp->firstname);
printf("Last Name: %s\n", tmp->lastname);
printf("Score: %d\n", tmp->score);
}
//free memory location
free(sptr);
return 0;
}
Enter detail of student #1 ID: s01 First Name: Last Name: Score: 8 Enter detail of student #2 ID: s02 First Name: Jane Last Name: Doe Score: 9 Enter detail of student #3 ID: s03 First Name: John Last Name: Doe Score: 7 Following are the student details: Detail of student #1 ID: s01 First Name: Last Name: Score: 8 Detail of student #2 ID: s02 First Name: Jane Last Name: Doe Score: 9 Detail of student #3 ID: s03 First Name: John Last Name: Doe Score: 7