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

前端 未结 6 1126
灰色年华
灰色年华 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: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);
    

提交回复
热议问题