Calloc () function in C

The function void * calloc (so-phan-tu, kich-co-phan-tu) allocates the requested memory and returns a pointer to it. The difference between malloc and calloc is: malloc does not set memory to 0 while calloc sets the allocated memory to 0.

The function void * calloc (so-phan-tu, kich-co-phan-tu) allocates the requested memory and returns a pointer to it. The difference between malloc and calloc is: malloc does not set memory to 0 while calloc sets the allocated memory to 0.

Declaring the function calloc () in C

Here is the declaration for calloc () in C:

 void * calloc ( so - phan - tu , kich - co - phan - tu ) 

Parameters

so-phan-tu : This is the number of elements to be allocated.

kich-co-phan-tu : This is the size of the element.

Returns the value

This function returns a pointer to the allocated memory, or returns NULL if the request fails.

For example

The following C program illustrates the usage of calloc () in C:

 #include #include int main () { int i , n ; int * a ; printf ( "Nhap so phan tu: n" ); scanf ( "%d" ,& n ); a = ( int *) calloc ( n , sizeof ( int )); printf ( "Nhap %d so: n" , n ); for ( i = 0 ; i < n ; i ++ ) { scanf ( "%d" ,& a [ i ]); } printf ( "Cac so vua nhap la: n" ); for ( i = 0 ; i < n ; i ++ ) { printf ( "%d " , a [ i ]); } return ( 0 ); } 

Compiling and running the above C program will result:

Calloc () function in C Picture 1Calloc () function in C Picture 1

According to Tutorialspoint

Previous lesson: Function strtoul () in C

Next lesson: Free () function in C

4 ★ | 1 Vote