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:

Picture 1 of Calloc () function in C

According to Tutorialspoint

Previous lesson: Function strtoul () in C

Next lesson: Free () function in C

You've just finished reading the article "Calloc () function in C" edited by the TipsMake team. You can save calloc-function-in-c.pdf to your computer here to read later or print it out. We hope this article has provided you with many useful tech tips and tricks. You can search for similar articles on tips and guides. Thank you for reading and for following us regularly.

« PREV : Free () function in...
Function strtoul ()... : NEXT »