void *calloc(unsigned n,unsigned size); 头文件为:stdlib.h函数
功 能: 在内存的动态存储区中分配n个长度为size的连续空间,函数返回一个指向分配起始地址的指针;若是分配不成功,返回NULL。指针
跟malloc的区别: calloc在动态分配完内存后,自动初始化该内存空间为零,而malloc不初始化,里边数据是随机的垃圾数据。而且malloc申请的内存能够是不连续的,而calloc申请的内存空间必须是连续的。code
示例代码:内存
<!-- lang: cpp --> #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char *pcName; pcName = (char *)calloc(10UL, sizeof(char)); printf("%s\n\n",pcName); printf("The length is %d\n",strlen(pcName)); return 0; }
malloc代码:string
<!-- lang: cpp --> #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char *pcName; pcName = (char *)malloc(10*sizeof(char)); printf("%s\n\n",pcName); printf("The length is %d\n",strlen(pcName)); return 0; }