Search code examples
carraysmemory-managementmallocrealloc

Using realloc to resize a dynamic array


I tried to extend my ful list of players.

When I use the realloc function, it save my player except the last. I mean that if I had 4 players in my array and I tried to extend my array to 7 I got a new array in size 7 and just 3 players.

This is part of the function:

void initializeListForTree(Player** players, int listSize)
{
    int formulaSize = bla bla bla.....
    players = (Player **)realloc(players, sizeof(Player *)*formulaSize);
    if (!players)
    {
        printf("memory allocation failed\n");
    }
}

Solution

  • More something like:

    void initializeListForTree(Player*** players, int listSize)
    {
    int formulaSize = bla bla bla.....
    void *p = realloc(*players, sizeof(Player *)*formulaSize);
    
      if (!p) {
          printf("memory allocation failed\n");
      }
      else {
        *players = p;
      }
    }
    

    and at the call site

    Player **playerslist = NULL;   
    
    initializeListForTree(&playerslist, 1);
     ...
    initializeListForTree(&playerslist, 2);
     etc..
    

    This, of course, only if your type is a pointer to a list of pointers.