calloc() 函数在 stdlib.h 头文件中定义。它有助于分配指定的内存并返回指向该内存的指针。calloc() 函数可以将分配的内存设置为零。
void *calloc(size_t nitems, size_t size); #where nitems should be a integer
calloc() 函数接受两个参数。此函数有助于分配多个大小相同且
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| nitems | 要分配的元素数量 | 必需 |
| size | 元素的大小 | 必需 |
calloc() 函数的
| 输入 | 返回值 |
|---|---|
| 成功 | 内存指针 |
| 失败 | NULL |
#include <stdio.h>
#include <stdlib.h>
int main()
{
int k, num;
int *p;
printf("count of entered elements :");
scanf("%d",&num);
p = (int*)calloc(num, sizeof(int));
printf("Enter %d numbers:\n",num);
for( k=0 ; k < num ; k++ ) {
scanf("%d",&p[k]);
}
printf("Entered elements are: ");
for( k=0 ; k < num ; k++ ) {
printf("%d ",p[k]);
}
free( p );
return(0);
}
输出
count of entered elements:3 Enter 3 numbers: 13 15 20 Entered elements are: 13 15 20
#include <stdio.h>
#include <stdlib.h>
int main (){
int k, * pt, t = 0;
pt = calloc(10, sizeof(int));
if (pt == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Sequence sum of the first 10 terms \ n ");
for (k = 0; k < 10; ++k) { * (pt + k) = k;
sum += * (pt + k);
}
printf("Sum = %d", t);
free(pt);
return 0;
}
输出
Sequence sum of the first 10 terms Sum = 45