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

匆匆过客 提交于 2019-11-27 14:24:38

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

dan04

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

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!