realloc vs malloc in C

不羁的心 提交于 2021-01-28 14:23:06

问题


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:

  1. Can realloc be used for anything else besides adding memory space to pointers?
  2. Does the size variable always have to be an int?
  3. 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:


  1. Yes, you can also reduce memory space
  2. Nah, why that? It takes void* as 1st parameter and returns void*
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!