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 << "Memory Allocation Failed";
      exit(1);
   }
   cout << "Initializing values..." << endl
        << endl;
   for (int i = 0; i < 5; i++) {
      ptr[i] = i * 2 + 1;
   }
   cout << "Initialized values" << endl;
   for (int i = 0; i < 5; i++) {
      /* ptr[i] and *(ptr+i) can be used interchangeably */
      cout << *(ptr + i) << endl;
   }
   free(ptr);
   return 0;
}

运行程序后,输出将是

Initializing values...

Initialized values
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 << "Null pointer";
   } else {
      cout << "Address = " << ptr << endl;
   }
   free(ptr);
   return 0;
}

运行程序后,输出将是

Address = 0x371530

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战