简体   繁体   English

将 calloc vs malloc 用于结构的动态数组

[英]using calloc vs malloc for dynamic array of struct

I've read that the difference between calloc and malloc is that calloc initializes the memory to the default value of the type declared.我读过 calloc 和 malloc 之间的区别是 calloc 将 memory 初始化为声明类型的默认值。

  1. For struct, what is the default value?对于struct,默认值是多少?
  2. Is there a difference between using calloc and malloc for dynamic array of struct?对动态结构数组使用 calloc 和 malloc 有区别吗?
  3. Would the members of the struct also be initialized?结构的成员也会被初始化吗?

calloc() will initialize the entire allocated memory range to zero. calloc()会将整个分配的内存范围初始化为零。 It has nothing to do with what type you are casting to.它与您要投射到的类型无关。

malloc() leaves the contents of the memory in an unspecified state. malloc()使内存的内容处于未指定状态。

The calloc function does not initialize memory to the default value for a given type, and in fact it can't because it knows nothing regarding the type that the memory will be used for.calloc功能不适用于给定类型初始化内存的默认值,而事实上它不能因为它知道有关该内存将被用于类型一无所获。

What it does do is set the memory to all bits 0. On most implementations you're likely to come across, this means that integer and floating point types will have the value 0 and that pointer types will be NULL.所做的设置内存的所有位0在大多数实现你很可能会遇到,这意味着,整数和浮点类型的值将是0和指针类型将是NULL。 With regard to structs and/or arrays, this would apply to any members, and additionally any padding within a struct would also have all bits set to 0.关于结构和/或数组,这将适用于任何成员,此外,结构内的任何填充也将所有位设置为 0。

calloc() will initialize the entire allocated memory range to zero. calloc() 会将整个分配的内存范围初始化为零。 It has nothing to do with what type you are casting to.它与您要投射到的类型无关。​ ​Malloc() function will create a single block of memory of size specified by the user. Malloc() 函数将创建用户指定大小的单个内存块。 Calloc() function can assign multiple blocks of memory for a variable. Calloc() 函数可以为一个变量分配多个内存块。 Malloc function contains garbage value. Malloc 函数包含垃圾值。 The memory block allocated by a calloc function is always initialized to zero. calloc 函数分配的内存块总是初始化为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM