C library function - calloc()
Description
C library function *void calloc(size_t nitems, size_t size) Allocates the required memory space and returns a pointer to it.malloc and calloc The difference between them is that malloc does not set the memory to zero, while calloc sets the allocated memory to zero.
**Note:** The calloc() function initializes all allocated memory to zero. If initialization is not needed, you can use the malloc() function instead. Also, when using calloc(), note that if the allocated memory block is too large, it may cause insufficient memory issues.
Declaration
The following is the declaration of the calloc() function.
void *calloc(size_t nitems, size_t size)
Parameters
- nitems -- Number of elements to be allocated.
- size -- Size of each element.
Return Value
The function returns a pointer to the allocated memory. If the request fails, it returns NULL.
Example
The following example demonstrates the use of the calloc() function.
Example
#include
<
stdio.h
#include
<
stdlib.h
int
main
(
)
{
int
i
,
n;
int
a
;
printf
(
"
Number of elements to input:
"
)
;
scanf
(
"
%d
"
,&
n
)
;
a
=
(
int
)
calloc
(
n
,
sizeof
(
int
)
)
;
printf
(
"
Enter %d numbers:
\
n
"
,
n
)
;
for
(
i
=
0
;
i
<
n
;
i
++
)
{
scanf
(
"
%d
"
,&
a
[
i
]
)
;
}
printf
(
"
The entered numbers are:
"
)
;
for
(
i
=
0
;
i
<
n
;
i
++
)
{
printf
(
"
%d
"
,
a
[
i
]
)
;
}
free
(
a
)
;
// Free memory
return
(
0
)
;
}
Let's compile and run the above program, which will produce the following result:
要输入的元素个数:3
Enter 3 numbers:
22
55
14
输入的数字为:22 55 14
C Standard Library -