c 库内存分配函数 void *calloc(size_t nitems, size_t size) 分配所请求的内存并返回指向它的指针。
malloc 和 calloc 的区别在于 malloc 不设置内存为零,而 calloc 将分配的内存设置为零。
内存分配函数
内存可以通过两种方式分配,如下所述 -
编译时分配内存后,执行期间不能更改。就会出现内存不足或者浪费的问题。
立即学习“C语言免费学习笔记(深入)”;
解决方案是动态创建内存,即在程序执行过程中根据用户的要求创建内存。
标准用于动态内存管理的库函数如下: -
- malloc ( )
- calloc ( )
- realloc ( )
- free ( )
Calloc ( ) 函数
该函数用于在运行时分配连续的内存块。
这是专门为数组设计的。
网奇Cwms企业网站程序1.0 1下载网奇CWMS企业网站管理系统 Company Website Manage System采用微软 ASP.NET2.0(C#) 设计,使用分层设计模式,页面高速缓存,是迄今为止国内最先进的.NET语言企业网站管理系统。整套系统的设计构造,完全考虑大中小企业类网站的功能要求,网站的后台功能强大,管理简捷,支持模板机制。使用国际编码,通过xml配置语言,一套系统可同时支持任意多语言。全站可生成各类模拟
它返回一个void指针,它指向分配的内存的基地址。
calloc()函数的语法如下 -
void *calloc ( numbers of elements, size in bytes)
示例
以下示例显示 calloc() 函数的用法。
int *ptr; ptr = (int * ) calloc (500,2);
这里,将连续分配 500 个大小为 2 字节的内存块。分配的总内存 = 1000 字节。

int *ptr; ptr = (int * ) calloc (n, sizeof (int));
示例程序
下面给出了一个使用动态内存分配函数Calloc计算一组元素中偶数和奇数之和的C程序。
在线演示
#include#include void main(){ //Declaring variables, pointers// int i,n; int *p; int even=0,odd=0; //Declaring base address p using Calloc// p = (int * ) calloc (n, sizeof (int)); //Reading number of elements// printf("Enter the number of elements : "); scanf("%d",&n); /*Printing O/p - We have to use if statement because we have to check if memory has been successfully allocated/reserved or not*/ if (p==NULL){ printf("Memory not available"); exit(0); } //Storing elements into location using for loop// printf("The elements are : "); for(i=0;i
",even); printf("The sum of odd numbers is : %d
",odd); }
输出
当执行上述程序时,会产生以下结果 -
Enter the number of elements : 4 The elements are : 12 56 23 10 The sum of even numbers is : 78 The sum of odd numbers is : 23










