How can I change the size of an array in C?

前端 未结 6 1068
灰色年华
灰色年华 2020-12-03 11:22

I am experimenting a little bit with gamestudio. I am making now a shooter game. I have an array with the pointer\'s to the enemies. I want. to when an enemy is killed. remo

相关标签:
6条回答
  • 2020-12-03 11:34

    As NickTFried suggested, Linked List is one way to go. Another one is to have a table big enough to hold the maximum number of items you'll ever have and manage that (which ones are valid or not, how many enemies currently in the list).

    As far as resizing, you'd have to use a pointer instead of a table and you could reallocate, copy over and so on... definitely not something you want to do in a game.

    If performance is an issue (and I am guessing it is), the table properly allocated is probably what I would use.

    0 讨论(0)
  • 2020-12-03 11:44

    You can't. This is normally done with dynamic memory allocation.

    // Like "ENEMY enemies[100]", but from the heap
    ENEMY* enemies = malloc(100 * sizeof(ENEMY));
    if (!enemies) { error handling }
    
    // You can index pointers just like arrays.
    enemies[0] = CreateEnemy();
    
    // Make the array bigger
    ENEMY* more_enemies = realloc(enemies, 200 * sizeof(ENEMY));
    if (!more_enemies) { error handling }
    enemies = more_enemies;
    
    // Clean up when you're done.
    free(enemies);
    
    0 讨论(0)
  • 2020-12-03 11:48

    Take a look at realloc which will allow you to resize the memory pointed to by a given pointer (which, in C, arrays are pointers).

    0 讨论(0)
  • 2020-12-03 11:50

    Arrays are static so you won't be able to change it's size.You'll need to create the linked list data structure. The list can grow and shrink on demand.

    0 讨论(0)
  • 2020-12-03 11:51

    Once an array in C has been created, it is set. You need a dynamic data structure like a Linked List or an ArrayList

    0 讨论(0)
  • 2020-12-03 11:59

    I wanted to lower the array size, but didn't worked like:

    myArray = new int[10];//Or so.
    

    So I've tried creating a new one, with the size based on a saved count.

    int count = 0;
    
    for (int i = 0; i < sizeof(array1)/sizeof(array1[0]); i++){
      if (array1[i] > 0) count++;
    }
    
    int positives[count];
    

    And then re-pass the elements in the first array to add them in the new one.

    //Create the new array element reference.
    
    int x = 0;
    
    for (int i = 0; i < sizeof(array1)/sizeof(array1[0]); i++){
      if (array1[i] > 0){ positives[x] = array1[i]; x++; }
    }
    

    And here we have a brand new array with the exact number of elements that we want (in my case).

    0 讨论(0)
提交回复
热议问题