C语言中的Calloc是什么?

c 库内存分配函数 void *calloc(size_t nitems, size_t size) 分配所请求的内存并返回指向它的指针。

malloc 和 calloc 的区别在于 malloc 不设置内存为零,而 calloc 将分配的内存设置为零。

内存分配函数

内存可以通过两种方式分配,如下所述 –

编译时分配内存后,执行期间不能更改。就会出现内存不足或者浪费的问题。

立即学习“C语言免费学习笔记(深入)”;

解决方案是动态创建内存,即在程序执行过程中根据用户的要求创建内存。

标准用于动态内存管理的库函数如下: –

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 字节。

C语言中的Calloc是什么?

int *ptr;ptr = (int * ) calloc (n, sizeof (int));

示例程序

下面给出了一个使用动态内存分配函数Calloc计算一组元素中偶数和奇数之和的C程序。

 在线演示

#include#includevoid 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 : 4The elements are :12562310The sum of even numbers is : 78The sum of odd numbers is : 23

以上就是C语言中的Calloc是什么?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1444878.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 21:58:23
下一篇 2025年12月17日 21:58:41

相关推荐

发表回复

登录后才能评论
关注微信