In C++, we can use the calloc()
function to allocate a block of memory. This allocated memory can be used for an array
of objects, and all the bits
are initialized to zero
.
void* calloc(size_t num, size_t size);
num
This represents the number of elements for which the memory block is allocated. It is an unsigned integral value.
size
This represents the size of each element in the allocated memory block in bytes
. It is an unsigned integral value.
size_t
is an unsigned integral type.
The method calloc()
returns the following cases:
A pointer to the first byte of the allocated memory block if allocation is successful.
A null pointer if allocation is failed.
calloc()
returnsvoid
. In order to convert it into other data type, we use typecasting.
#include <cstdlib>
//Including headers#include <cstdlib>#include <iostream>using namespace std;int main() {//Allocating memory blockint* ptr = (int*)calloc(10, sizeof(int));//Checking for failureif (!ptr) {cout << "Failed to allocated memory\n";exit(1);}//Initializing allocated memoryfor (int i = 0; i < 10; i++) {ptr[i] = i;}//Printing allocated memoryfor (int j = 0; j < 10; j++) {cout << *(ptr + j) << endl;}//ptr[i] and *(ptr+i) are same//Deallocating allocated memoryfree(ptr);return 0;}