c 库内存分配函数 void *calloc(size_t nitems, size_t size) 分配所请求的内存并返回指向它的指针。
malloc 和 calloc 的区别在于 malloc 不设置内存为零,而 calloc 将分配的内存设置为零。
内存可以通过两种方式分配,如下所述 -
编译时分配内存后,执行期间不能更改。就会出现内存不足或者浪费的问题。
立即学习“C语言免费学习笔记(深入)”;
解决方案是动态创建内存,即在程序执行过程中根据用户的要求创建内存。
标准用于动态内存管理的库函数如下: -
该函数用于在运行时分配连续的内存块。
这是专门为数组设计的。
它返回一个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<stdio.h>
#include<stdlib.h>
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 : </p><p>");
for(i=0;i<n;i++){
scanf("%d",p+i);
}
for(i=0;i<n;i++){
if(*(p+i)%2==0){
even=even+*(p+i);
} else {
odd=odd+*(p+i);
}
}
printf("The sum of even numbers is : %d</p><p>",even);
printf("The sum of odd numbers is : %d</p><p>",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
以上就是C语言中的Calloc是什么?的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号