请输入您要查询的百科知识:

 

词条 calloc
释义

函数简介

calloc是一个C语言函数

函数名: calloc

void *calloc(unsigned n,unsigned size);

功 能: 在内存的动态存储区中分配n个长度为size的连续空间,函数返回一个指向分配起始地址的指针;如果分配不成功,返回NULL。

跟malloc的区别:

calloc在动态分配完内存后,自动初始化该内存空间为零,而malloc不初始化,里边数据是随机的垃圾数据。

用 法: void *calloc(unsigned n,unsigned size);

头文件:stdlib.h或malloc.h

相关函数:malloc、realloc、free

应用举例

程序例1

#include <stdlib.h>

#include<string.h>

#include <stdio.h>

int main(void)

{

char *str = NULL;

/* 分配内存空间 */

str = (char*)calloc(10, sizeof(char));

/* 将hello写入*/

strcpy(str, "Hello");

/*显示变量内容*/

printf("String is %s\", str);

/* 释放空间 */

free(str);

return 0;

}

程序例2

从这个例子可以看出calloc分配完存储空间后将元素初始化。

#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++);

printf("\");

free(pn);

return 0;

}

输出十个0。

随便看

 

百科全书收录4421916条中文百科知识,基本涵盖了大多数领域的百科知识,是一部内容开放、自由的电子版百科全书。

 

Copyright © 2004-2023 Cnenc.net All Rights Reserved
更新时间:2025/3/22 7:41:07