【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:
- #define FIRST_DEMO
-
-
- #ifdef FIRST_DEMO
- #include <stdio.h>
- #include <conio.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);
- getch();
- return 0;
- }
- #elif defined SECOND_DEMO
- #include <stdio.h>
- #include <conio.h>
- #include <stdlib.h>
- int main(void)
- {
- int i,n;
- int *pData;
- printf("Amount of numbers to be entered:");
- scanf("%d",&i);
- pData=(int *)calloc(i,sizeof(int));
- if (pData == NULL)
- {
- exit(1);
- }
- for (n=0;n<i;n++)
- {
- printf("Enter number #%d:",n);
- scanf("%d",&pData[n]);
- }
- printf("You have entered: ");
- for (n=0;n<i;n++)
- {
- printf("%d ",pData[n]);
- }
- free(pData);
- getch();
- return 0;
- }
- #endif