C++ calloc() 函数
calloc()
函数在分配成功时返回指向分配的内存块第一个字节的指针。
如果大小为零,返回的值取决于库的实现。它可能是也可能不是空指针。
calloc() 函数原型
void* calloc(size_t num, size_t size);
该函数定义在 <cstdlib>
头文件中。
calloc() 参数
- num: 一个无符号整数值,表示元素的数量。
- size: 一个无符号整数值,表示以字节为单位的内存块大小。
calloc() 返回值
calloc()
函数返回:
- 指向函数分配的内存块起始位置的指针。
- 如果分配失败,则返回空指针。
示例 1:calloc() 函数如何工作?
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int *ptr;
ptr = (int *)calloc(5, sizeof(int));
if (!ptr) {
cout << "内存分配失 败";
exit(1);
}
cout << "初始化值..." << endl
<< endl;
for (int i = 0; i < 5; i++) {
ptr[i] = i * 2 + 1;
}
cout << "已初始化值" << endl;
for (int i = 0; i < 5; i++) {
/* ptr[i] 和 *(ptr+i) 可以互换使用 */
cout << *(ptr + i) << endl;
}
free(ptr);
return 0;
}
当你运行程序时,输出将是:
初始化值...
已初始化值
1
3
5
7
9
示例 2:calloc() 函数的大小为零时
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int *ptr = (int *)calloc(0, 0);
if (ptr == NULL) {
cout << "空指针";
} else {
cout << "地址 = " << ptr << endl;
}
free(ptr);
return 0;
}
当你运行程序时,输出将是:
地址 = 0x371530