calloc函数(转载)

 

C语言之calloc函数

标签: callocfreemalloc
  1670人阅读  评论(0)  举报
  分类:

【FROM MSDN && 百科】

原型: void *calloc(size_t  n,size_t size);

#include<stdlib.h>或#include <malloc.h>

在内存的动态内存区中分配n个长度为size的连续空间,函数返回一个指向分配起始地址指针;如果分配不成功,返回NULL。

与malloc的区别是:calloc在动态分配完内存后,自动初始化该内存空间为零,而malloc不初始化,里边数据是随机的垃圾数据。

Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.
The effective result is the allocation of an zero-initialized memory block of (num*size) bytes.

DEMO:

[cpp]  view plain  copy
  1. #define FIRST_DEMO  
  2. //#define SECOND_DEMO  
  3.   
  4. #ifdef FIRST_DEMO  
  5. #include <stdio.h>  
  6. #include <conio.h>  
  7. #include <stdlib.h>  
  8. /*this demo :calloc allocate block of memory zero-initialized*/  
  9. int main(void)  
  10. {  
  11.     int i;  
  12.     int *pn=(int *)calloc(10,sizeof(int));  
  13.     for (i=0;i<10;i++)  
  14.     {  
  15.         printf("%3d",pn[i]);  
  16.     }  
  17.     printf("\n");  
  18.     free(pn);  
  19.     getch();  
  20.     return 0;  
  21. }  
  22. #elif defined SECOND_DEMO  
  23. #include <stdio.h>  
  24. #include <conio.h>  
  25. #include <stdlib.h>  
  26. int main(void)  
  27. {  
  28.     int i,n;  
  29.     int *pData;  
  30.     printf("Amount of numbers to be entered:");  
  31.     scanf("%d",&i);  
  32.     pData=(int *)calloc(i,sizeof(int));  
  33.     if (pData == NULL)  
  34.     {  
  35.         exit(1);  
  36.     }  
  37.     for (n=0;n<i;n++)  
  38.     {  
  39.         printf("Enter number #%d:",n);  
  40.         scanf("%d",&pData[n]);  
  41.     }  
  42.     printf("You have entered: ");  
  43.     for (n=0;n<i;n++)  
  44.     {  
  45.         printf("%d ",pData[n]);  
  46.     }  
  47.     free(pData);  
  48.     getch();  
  49.     return 0;  
  50. }  
  51. #endif  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值