我想使用 malloc
在堆中创建动态数组。
int *c = malloc(5 * sizeof(int));
问题是它不初始化为零,我想尽可能避免使用calloc
,因为我不知道它有多安全.
如果我使用calloc
,它会执行相同的malloc
工作吗?
最佳答案
malloc():
malloc()
有一个争论:要分配的字节数。分配的字节未初始化。因此,它们的值可以是 0-255 之间的任何值,或这些数字的任意组合。 不要指望任何事情!
代码示例:
int *mem = malloc(5 * sizeof(int));
<小时/>
calloc():
calloc()
有两个参数:要为其分配内存的元素数量以及需要为每个元素分配的内存数量。它将每个字节初始化为零。
代码示例:
int *mem = calloc(5, sizeof(int));
来自C 编程语言 ~ Brian W. Kernighan 和 Dennis M. Ritchie:
void *calloc(size_t nobj, size_t size)
calloc returns a pointer to space for an array of nobj objects,
each of size size, or NULL if the request cannot be satisfied.
The space is initialized to zero bytes.
[强调我的]
<小时/>或者,您可以使用 memset()
初始化内存
#include <string.h> // for memset()
//allocate memory
int *mem = malloc(5 * sizeof(int));
//initialize memory to zeros
memset(mem, 0, 5 * sizeof(int));
关于c - 将 malloc 初始化为零,而不是使用 calloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39381237/