首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::calloc

Defined in header <cstdlib>

?

?

void* calloc( std::size_t num, std::size_t size );

?

?

的数组分配内存。num尺寸对象size并将其初始化为所有零位。

如果分配成功,则返回一个指针,指向分配的内存块中的最低%281%29字节,该指针适合于任何对象类型。

如果size为零,则可以返回已定义为%28空指针的行为,或者可能返回一些可能不用于访问存储%29的非空指针。

The following functions are required to be thread-safe: The library versions of operator new and operator delete User replacement versions of global operator new and operator delete std::calloc, std::malloc, std::realloc, std::aligned_alloc (since C++17) Calls to these functions that allocate or deallocate a particular unit of storage occur in a single total order, and each such deallocation call happens-before the next allocation (if any) in this order.

(since C++11)

  • 的库版本operator newoperator delete
  • 全局用户替换版本operator newoperator delete
  • std::calloc,,,std::malloc,,,std::realloc,,,std::aligned_alloc%28自C++17%29

对分配或释放特定存储单元的这些函数的调用是以单个总顺序进行的,并且每个这样的释放调用都会发生。发生-之前下一次按此顺序分配%28(如果有%29)。

%28自C++11%29

参数

num

-

number of objects

size

-

size of each object

返回值

成功后,返回指向新分配内存开始的指针。返回的指针必须用std::free()std::realloc()...

失败时,返回一个空指针。

注记

由于对齐需求,分配的字节数不一定等于num*size...

初始化到所有位零并不保证浮点或指针将分别初始化为0.0和空指针值(分别为%28),尽管在所有常见平台%29上都是如此。

最初在C89%29中添加了对零大小的支持,以适应如下代码。

二次

代码语言:javascript
复制
OBJ *p = calloc(0, sizeof(OBJ)); // "zero-length" placeholder
...
while(1) { 
    p = realloc(p, c * sizeof(OBJ)); // reallocations until size settles
    ... // code that may change c or break out of loop
}

二次

二次

代码语言:javascript
复制
#include <iostream>
#include <cstdlib>
 
int main()
{
    int* p1 = (int*)std::calloc(4, sizeof(int)); // allocate and zero out an array of 4 int
    int* p2 = (int*)std::calloc(1, sizeof(int[4])); // same, naming the array type directly
    int* p3 = (int*)std::calloc(4, sizeof *p3);   // same, without repeating the type name
 
    if(p2)
        for(int n=0; n<4; ++n) // print the array
            std::cout << "p2[" << n << "] == " << p2[n] << '\n';
 
    std::free(p1);
    std::free(p2);
    std::free(p3);
}

二次

产出:

二次

代码语言:javascript
复制
p2[0] == 0
p2[1] == 0
p2[2] == 0
p2[3] == 0

二次

另见

c Calloc文件

*。

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com