在C中重新分配vs malloc [英] realloc vs malloc in C
问题描述
我对C语言还很陌生,现在刚开始涉足动态分配数组的领域.
I'm fairly new to C, and just now starting to venture into the realm of dynamically allocated arrays.
我认为我大多数情况下是 malloc
,但是对 realloc
有一些疑问:
I think i've got mostly malloc
down, but had some questions on realloc
:
- 除了向指针添加内存空间之外,
realloc
还能用于其他任何用途吗? - size变量是否总是必须为
int
? -
是否可以进行以下工作?
- Can
realloc
be used for anything else besides adding memory space to pointers? - Does the size variable always have to be an
int
? Would something like the below work?
float *L = NULL;
int task_count = 5;
L = (float*) realloc (L, task_count * sizeof(float));
如果我想进一步增加该空间(在这种情况下增加一倍),是否可以使用如下所示的内容?
If I wanted to increase that space further (by one in this case), could I just use something like the following?
L = (float*) realloc (L, 1 * sizeof(float));
看似简单,这告诉我我可能丢失了一些东西.
Seems deceptively simple, which tells me I'm possibly missing something.
推荐答案
如果ptr是空指针,则该函数的行为类似于malloc,分配一个新的大小为字节的块,并返回一个指向其开头的指针.
In case that ptr is a null pointer, the function behaves like malloc, assigning a new block of size bytes and returning a pointer to its beginning.
void * realloc (void* ptr, size_t size);
ptr-指向先前分配有malloc,calloc或 realloc 的内存块的指针.或者,它可以是一个空指针,在这种情况下,将分配一个新块(就像malloc被调用).
ptr - Pointer to a memory block previously allocated with malloc, calloc or realloc. Alternatively, this can be a null pointer, in which case a new block is allocated (as if malloc was called).
sizeNew-内存块的大小,以字节为单位.size_t是无符号整数类型.
sizeNew - size for the memory block, in bytes. size_t is an unsigned integral type.
sizeNew必须定义您想要的整个内存,可以更小,也可以更大!
sizeNew has to define the entirety of the memory you want, could be smaller, could be larger!
这篇关于在C中重新分配vs malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!