In this guide, you will learn what is calloc() function is in C++ programming and how to use it with an example.
1. calloc() Function Overview
The calloc() function is used to allocate memory for an array of elements, each of a certain size. The memory is set to zero. Like malloc(), the memory allocated by calloc() needs to be released by the programmer using the free() function. It's a part of the C standard library <cstdlib> in C++ and is utilized when we need to allocate memory dynamically for arrays and ensure that the allocated memory is zero-initialized.
Signature:
void* calloc(size_t num, size_t size);
Parameters:
- num: Number of elements to allocate.
- size: Size of each element in bytes.
2. Source Code Example
#include <iostream>
#include <cstdlib>
int main() {
int* arr;
int n = 5; // Number of integers
// Dynamically allocate memory for 5 integers using calloc
arr = (int*) calloc(n, sizeof(int));
if(arr == NULL) {
std::cerr << "Memory allocation failed." << std::endl;
return 1;
}
// Print the array (Should print zeros)
for(int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
// Assign values to the allocated memory
for(int i = 0; i < n; i++) {
arr[i] = i + 1;
}
std::cout << std::endl;
// Print the array after assignment
for(int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
// Free the allocated memory
free(arr);
return 0;
}
Output:
0 0 0 0 0 1 2 3 4 5
3. Explanation
1. We declare an integer pointer named arr to hold the address of the first byte of allocated memory.
2. Using calloc(), we dynamically allocate memory for 5 integers and initialize them to zero.
3. We then check if memory allocation was successful by comparing arr to NULL.
4. Initially, we print the values in the array, which should all be zeros since calloc() initializes the memory to zero.
5. We then assign values to the allocated memory and print the contents.
6. After utilizing the dynamically allocated memory, we release it using the free() function.
Comments
Post a Comment