Question

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.

No correct solution

OTHER TIPS

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!

  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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top