calloc stands for contiguous allocation. It allocates memory for an array of elements and also initializes all the bits in the allocated memory to zero. It’s useful when you need a zero-initialized array or structure.
Syntax:
void* calloc(size_t num, size_t size);
Explanation:
num: The number of elements you want to allocate memory for.
size: The size of each element in bytes.
Returns a pointer to the allocated memory, or NULL if allocation fails.
Example:
int* arr = (int*) calloc(20, sizeof(int)); // Allocates and initializes an array of 20 integers to 0
This allocates memory for 20 integers and sets all of them to 0 automatically.
C calloc function – Interview Questions
Q 1: What is calloc()?
Ans: Allocates multiple blocks of memory and initializes them to zero.
Q 2: What is the syntax of calloc()?
Ans: calloc(n, size);
Q 3: Does calloc() initialize memory?
Ans: Yes, with zero.
Q 4: What is the return type of calloc()?
Ans: void*.
Q 5: Which is slower: malloc() or calloc()?
Ans: calloc() is slightly slower.
C calloc function – Objective Questions (MCQs)
Q1. What does the calloc() function do?
Q2. What is the correct syntax for calloc()?
Q3. What is the difference between malloc() and calloc()?
Q4. What will calloc() return if memory allocation fails?
Q5. If ptr = calloc(5, sizeof(int));, how many bytes are allocated (assuming int = 4 bytes)?