Calloc in C++Calloc is used to allocate the memory to the variables or arrays dynamically. It initializes the memory to zero. It is popularly used in C language, but it can also be used in C++. In C++ language, we use keywords like new function new[] for memory allocation for elements and an array of elements. We can also use the calloc function for memory allocation in C++. This calloc function can be found in the <cstdlib> header file. Syntax of the calloc function in C++:It has the following syntax: Parameters passed to the calloc function are:number_of_elements:
Size_of_elements:
The return value of the calloc function are:
Example:Let's take a simple program to demonstrate the usage of the calloc() function in C++: Output: Explanation: In the above C++ program, we first included the header files like <cstdlib> and <iostream>. In the main function, we used the calloc function for memory allocation where the number of elements is given as 5, and the size of each element will be equal to the size of the int. The return value of the calloc will be a pointer and is given to the ptr. Now, we check whether the ptr is the null pointer or not. If it is a null pointer an error message is displayed, we fill the memory blocks with the values. At last, we printed the elements. After that, we used the free() function to erase the memory that is allocated. Example:A program if calloc() function with size zero; Output: Explanation: In the above program, we used the calloc function to allocate the memory dynamically. Here, we used a function to allocate the memory of an array of zero elements with each element having 0 bytes. The output will be a hexadecimal memory address, which indicates the memory location in the memory space. This address is implementation-specific and can vary between different systems and compilers. We also used free() function to free the memory allocated. Example:A program to illustrate the working of calloc() function: Output: Explanation: This C++ program lets the user to input the size and values of two matrices. It creates memory space for these matrices using calloc, adds the matrices together, and shows the result. First, it sets aside memory for the matrices based on the user's size specifications. After that, it takes the user's input to fill both matrices. After that, it adds the numbers in the corresponding positions of the two matrices to generate a new matrix. Finally, it cleans up by releasing the allocated memory to avoid any memory-related issues. In essence, this program allows you to add two matrices and see the outcome of the program. Next TopicMultiplication Table in C++ |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India