I’m trying to add 10 more elements to my struct that has been already malloc with a fixed sized of 20. This is the way I have my struct defined:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct st_temp {
char *prod;
};
int main ()
{
struct st_temp **temp_struct;
size_t j;
temp_struct = malloc (sizeof *temp_struct * 20);
for (j = 0; j < 20; j++) {
temp_struct[j] = malloc (sizeof *temp_struct[j]);
temp_struct[j]->prod = "foo";
}
return 0;
}
So what I had in mind was to realloc as (however, not sure how to):
temp_struct = (struct st_temp **) realloc (st_temp, 10 * sizeof(struct st_temp*));
and then add the extra 10 elements,
for (j = 0; j < 10; j++)
temp_struct[j]->prod = "some extra values";
How could I achieve this? Any help is appreciated!
To avoid memory leaks, we need to handle reallocating with care (more on that later). The realloc function:
void *realloc(void *ptr, size_t size), whereptr= the pointer to the original (malloc‘ed) memory block, andsize= the new size of the memory block (in bytes).reallocreturns the new location of the dynamically allocated memory block (which may have changed) – or NULL if the re-allocation failed! If it returns NULL, the original memory stays unchanged, so you must always use a temporary variable for the return value ofrealloc.An example will clarify this a bit (points of interest: realloc syntax is similar to malloc’s (no need for extra casts etc.) and, after realloc, you need to produce the same steps for the new objects as you did after malloc):
Do note, that this is not really an array of structs, but more an array of pointers to structs – or even an array of arrays of struct if you wish. In the last case, each sub-array would be of length 1 (since we only allocate space for one struct).