1 函数原型
calloc():分配内存块,函数原型如下:
void* calloc (size_t num, size_t size);
cstdlib库描述如下:
Allocate and zero-initialize array
1. Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.
2. The effective result is the allocation of a zero-initialized memory block of (num*size) bytes.
3. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.
- calloc()函数和malloc()函数都用于动态内存分配,区别在于:
(1)初始化:calloc()函数分配的内存块会被初始化为0,而malloc()函数分配的内存块是未初始化的;
(2)参数:calloc()函数接受两个参数num和size,num表示要分配的元素的数量,size表示要分配的元素的大小(单位为字节),申请分配的内存块大小为num*size个字节;malloc()函数只接受一个参数size,表示申请分配的内存块大小为size个字节。
2 参数
calloc()函数有两个参数num和size:
- 参数num是要分配的元素的数量,类型为size_t;
- 参数size是要分配的元素的大小,单位为字节,类型为size_t。
cstdlib库描述如下:
num
1. Number of elements to allocate.
size
1. Size of each element.
size_t is an unsigned integral type.
3 返回值
calloc()函数的返回值类型为void*型:
- 分配成功,返回指向新分配的内存块的指针;
- 分配失败,返回NULL。
cstdlib库描述如下:
1. On success, a pointer to the memory block allocated by the function.
2. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
3. If the function failed to allocate the requested block of memory, a null pointer is returned.
4 示例
示例代码如下所示:
int main() {
int main() {
//
int* arr = NULL;
int n = 0;
int i = 0;
//
printf("请输入数组的大小: ");
scanf("%d", &n);
// 使用 calloc 分配 n 个 int 类型的内存
arr = (int*)calloc(n, sizeof(int));
// 检查 calloc 是否成功
if (arr == NULL) {
printf("内存分配失败!\n");
return 1; // 返回非零值表示错误
}
// 打印数组初始值
printf("数组初始值是:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// 输入数组元素
printf("请输入 %d 个整数:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// 输出数组元素
printf("您输入的数组是:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// 释放分配的内存
free(arr);
// 将arr设置为NULL
arr = NULL;
//
return 0;
}
代码运行结果如下图所示:
代码及运行结果分析如下:
- calloc()函数分配的内存块会被初始化为0。