views:

100

answers:

5

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. remove him from the list. And I also want to be able to create new enemies.

Gamestudio uses a scripting language named lite-C. It has the same syntax as C and on the website they say, that it can be compiled with any C compiler. It is pure C, no C++ or anything else.

I am new to C. I normally program in .NET languages and some scripting languages,

+1  A: 

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

NickTFried
A: 

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).

dj2
I believe for this to work the array must be an array allocated by malloc, not on the stack. And also be warned that if it fails to allocate in-place it will free the old block and allocate a new block. This invalidates any pointers into the original block.
Michael Anderson
Ah, yea. Both of those need to be taken into account if you're going to use realloc.
dj2
+1  A: 

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.

blakejc70
A: 

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.

Matthieu
It's still an array implementation of a list. You're right though, it requires knowledge of the max array size.
blakejc70
+5  A: 

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));

// You can index pointers just like arrays.
enemies[0] = CreateEnemy();

// Make the array bigger
enemies = realloc(enemies, 200 * sizeof(ENEMY));

// Clean up when you're done.
free(enemies);
dan04
`x = realloc(x, ...)` is a memory leak waiting to happen. (However, I realize that demonstrating how to handle dynamic allocation failures wasn't the point of this answer.)
bk1e
True, and I should have checked whether `malloc` returns `NULL` as well.
dan04