一,函数的说明
头文件: stdlib.h或malloc.h
功 能:在内存的动态存储区堆中中分配n个长度为size的连续空间,函数返回一个指向分配起始地址的指针;如果分配不成功,返回NULL。
calloc在动态分配完内存后,自动初始化该内存空间为零,而malloc不初始化,里边数据是随机的垃圾数据。
二,使用例子
例1
#include <stdlib.h> #include <string.h> #include <stdio.h> int main(void) { char[16] sz = "hello word"; char * p_str = NULL; /* 分配内存空间 */ p_str = (char*)calloc(20, sizeof(char)); if(!p_str) { printf("calloc memory fails!\n"); return -1; } /* 将helloword写入*/ strncpy(p_str, sz, 20); /*显示变量内容*/ printf("string is %s\n", p_str); /* 释放空间 */ free(p_str); return 0; }
#include<stdio.h> #include<stdlib.h> int main(void) { int i; int *pn = ( int *)calloc(10,sizeof(int)); for(i=0;i<10;i++) { printf("%3d",pn[i]); } printf("\n"); free(pn); return 0; } 输出十个0。