问题
I'm fairly new to C, and just now starting to venture into the realm of dynamically allocated arrays.
I think i've got mostly malloc
down, but had some questions on realloc
:
- 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.
回答1:
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 - 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 for the memory block, in bytes. size_t is an unsigned integral type.
sizeNew has to define the entirety of the memory you want, could be smaller, could be larger!
回答2:
- Yes, you can also reduce memory space
- Nah, why that? It takes void* as 1st parameter and returns void*
- Yes, but no need to cast!
And finally, you have to tell the total memory sizeto the function.
来源:https://stackoverflow.com/questions/22131381/realloc-vs-malloc-in-c