Resizing an array with C

前端 未结 3 550
后悔当初
后悔当初 2020-11-28 07:26

I need to have an array of structs in a game I\'m making - but I don\'t want to limit the array to a fixed size. I\'m told there is a way to use realloc to make the array bi

3条回答
  •  难免孤独
    2020-11-28 08:23

    From http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/

    /* realloc example: rememb-o-matic */
    #include 
    #include 
    
    int main ()
    {
      int input,n;
      int count=0;
      int * numbers = NULL;
    
      do {
         printf ("Enter an integer value (0 to end): ");
         scanf ("%d", &input);
         count++;
         numbers = (int*) realloc (numbers, count * sizeof(int));
         if (numbers==NULL)
           { puts ("Error (re)allocating memory"); exit (1); }
         numbers[count-1]=input;
      } while (input!=0);
    
      printf ("Numbers entered: ");
      for (n=0;n

提交回复
热议问题