gpt4 book ai didi

c - C 中的 Realloc 分配

转载 作者:太空宇宙 更新时间:2023-11-04 05:40:16 25 4
gpt4 key购买 nike

你好,我想了解 realloc 是如何工作的,所以这是我的问题:

假设我们首先调用 malloc 以便为 1 个 int 分配足够的内存。

int *p=malloc(sizeof(int))

然后我们这样调用realloc:

p=realloc(p,sizeof(int)*2);

指针 p 指向具有 2 或 1+2 整数可用空间的内存?

最佳答案

the man pages 中所述:

void *realloc(void *ptr, size_t size);

[...]

The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized. [...]

(我的重点)。换句话说,realloc 的大小参数询问的是您总共要分配多少字节的内存,而不是您要添加的内存字节数。

希望这对您有所帮助!

关于c - C 中的 Realloc 分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20940334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com