calloc ()- 保留并初始化存储器
格式
#include <stdlib.h>
void *calloc(size_t num, size_t size);语言级别
ANSI
线程安全
是
描述
calloc() 函数为 num 元素数组保留存储空间,每个元素的长度为 size 字节。 然后, calloc() 函数为每个元素的所有位提供 0的初始值。
返回值
calloc() 函数返回指向保留空间的指针。 返回值所指向的存储空间适合用于存储任何类型的对象。 要获取指向类型的指针,请在返回值上使用强制类型转换。 如果没有足够的存储空间,或者如果 num 或 size 为 0,那么返回值为 NULL 。
注:
- 所有堆存储器都与调用函数的激活组相关联。 因此,应该在同一激活组中分配,取消分配和重新分配存储器。 不能在一个激活组中分配堆存储器,也不能从另一个激活组中取消分配或重新分配该存储器。 有关激活组的更多信息,请参阅 ILE 概念 手册。
- 要在不更改 C 源代码的情况下使用 太字节空间 存储器而不是单层存储器,请在编译器命令上指定 TERASPACE (*YES *TSIFC) 参数。 这会将
calloc()库函数映射到_C_TS_calloc()(其太字节空间存储器对等项)。 每次调用_C_TS_calloc()可分配的最大太字节空间存储量为 2GB -224 或 2147483424 字节。有关太字节空间存储器的更多信息,请参阅 ILE Concepts 手册。
- 如果已在当前激活组中启用快速池内存管理器,那么将使用快速池内存管理器检索存储器。 请参阅_C_Quickpool_Init ()-初始化快速池内存管理器 以获取更多信息。
示例
此示例提示输入所需的数组条目数,然后在存储器中为这些条目保留足够的空间。 如果
calloc() 成功,那么示例将显示每个条目; 否则,将显示错误。#include <stdio.h>
#include <stdlib.h>
int main(void)
{
long * array; /* start of the array */
long * index; /* index variable */
int i; /* index variable */
int num; /* number of entries of the array*/
printf( "Enter the size of the array\n" );
scanf( "%i", &num);
/* allocate num entries */
if ( (index = array = (long *) calloc( num, sizeof( long ))) != NULL )
{
for ( i = 0; i < num; ++i ) /* put values in arr */
*index++ = i; /* using pointer no */
for ( i = 0; i < num; ++i ) /* print the array out */
printf( "array[%i ] = %i\n", i, array[i] );
}
else
{ /* out of storage */
perror( "Out of storage" );
abort();
}
}
/****************** Output should be similar to: **********************
Enter the size of the array
array[ 0 ] = 0
array[ 1 ] = 1
array[ 2 ] = 2
*/