How to allocate more space for my array of C structures?

I'm trying to add 10 more elements to my structure, which was already malloc with a fixed size of 20. This is how I defined my structure:

#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, I meant redistribution as (however, not sure how):

temp_struct = (struct st_temp **) realloc (st_temp, 10 * sizeof(struct st_temp*));

and then add an additional 10 items,

   for (j = 0; j < 10; j++)
      temp_struct[j]->prod = "some extra values";

How could I achieve this? Any help is appreciated!

+5
source share
2 answers

To avoid memory leaks, we need to handle redistribution with caution (more on this later). Realloc function:

void *realloc(void *ptr, size_t size)where

ptr= pointer to the original memory block ( malloc'ed) and

size= new size of the memory block (in bytes).

realloc ( ) - NULL, ! NULL, , realloc.

( : realloc malloc ( ..), realloc , ):

struct st_temp **temp_struct;
temp_struct = malloc(20 * sizeof *temp_struct);
if (temp_struct == NULL) { /* handle failed malloc */ }
for (int i = 0; i < 20; ++i) {
    temp_struct[i] = malloc(sizeof *temp_struct[i]);
    temp_struct[i]->prod = "foo";
}

// We need more space ... remember to use a temporary variable
struct st_temp **tmp;
tmp = realloc(temp_struct, 30 * sizeof *temp_struct);
if (tmp == NULL) { 
    // handle failed realloc, temp_struct is unchanged
} else {
    // everything went ok, update the original pointer (temp_struct)
    temp_struct = tmp; 
}
for (int i = 20; i < 30; ++i) { // notice the indexing, [20..30)
    // NOTICE: the realloc allocated more space for pointers
    // we still need to allocate space for each new object
    temp_struct[i] = malloc(sizeof *temp_struct[i]);
    temp_struct[i]->prod = "bar";
}
// temp_struct now "holds" 30 temp_struct objects
// ...
// and always do remember, in the end
for (int i = 0; i < 30; ++i)
    free(temp_struct[i]);
free(temp_struct);

, , - , . 1 ( ).

+5

realloc(), . :

temp_struct = (struct st_temp **) realloc (temp_struct, 30 * sizeof(struct st_temp*));

30 - , , 20 10. realloc() , .

10 - ( 20, 0):

for (j = 20; j < 30; j++) {
    temp_struct[j]->prod = "some extra values"; 
}
+8

All Articles