C语言中的calloc函数是什么?
C库内存分配函数 `void *calloc(size_t nitems, size_t size)` 分配请求的内存并返回指向它的指针。
malloc和calloc的区别在于,malloc不将内存设置为零,而calloc将分配的内存设置为零。
内存分配函数
内存分配方式如下所示:

一旦在编译时分配了内存,就不能在执行期间更改它。这会导致内存不足或浪费。
解决方案是在程序执行期间根据用户的需求动态创建内存。
用于动态内存管理的标准库函数如下:
- malloc()
- calloc()
- realloc()
- free()
calloc() 函数
此函数用于在运行时分配连续的内存块。
它专门为数组设计。
它返回一个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));
示例程序
下面是一个C程序,它使用动态内存分配函数calloc计算一组元素中偶数和奇数的和。
#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 :
");
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
",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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP