C語言之calloc函數

【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
//#define SECOND_DEMO

#ifdef FIRST_DEMO
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
/*this demo :calloc allocate block of memory zero-initialized*/
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


發佈了90 篇原創文章 · 獲贊 68 · 訪問量 66萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章