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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值