如何更改 C 中数组的大小?
我正在用 gamestudio 进行一些实验。 我现在正在制作一款射击游戏。 我有一个数组,其中包含指向敌人的指针。当敌人被杀死时,我想将他从列表中删除。我也希望能够创造新的敌人。
Gamestudio 使用名为 lite-C 的脚本语言。它具有与 C 相同的语法,并且在网站上他们说它可以使用任何 C 编译器进行编译。它是纯 C 语言,没有 C++ 或其他任何东西。
我是 C 语言新手。我通常使用 .NET 语言和一些脚本语言进行编程。
I am experimenting a little bit with gamestudio.
I am now making a shooter game.
I have an array with the pointers to the enemies. When an enemy is killed, I want to 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你不能。这通常是通过动态内存分配来完成的。
You can't. This is normally done with dynamic memory allocation.
C 中的数组一旦创建,就被设置。您需要一个动态数据结构,例如链接列表或数组列表
Once an array in C has been created, it is set. You need a dynamic data structure like a Linked List or an ArrayList
数组是静态的,因此您无法更改其大小。您需要创建链接列表数据结构。该列表可以根据需要增长和缩小。
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.
看一下
realloc
,它允许您调整给定指针(在 C 中,数组就是指针)指向的内存大小。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).正如 NickTFried 所建议的,链接列表是一种方法。
另一种方法是拥有一张足够大的桌子来容纳您将拥有的最大数量的物品并对其进行管理(哪些物品有效或无效,列表中当前有多少敌人)。
至于调整大小,你必须使用指针而不是表格,并且你可以重新分配、复制等等......绝对不是你想要在游戏中做的事情。
如果性能是一个问题(我猜是这样),那么正确分配的表可能就是我会使用的。
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.
我想降低数组大小,但效果不佳:
所以我尝试创建一个新数组,其大小基于保存的计数。
然后重新传递第一个数组中的元素以将它们添加到新数组中。
这里我们有一个全新的数组,其中包含我们想要的确切元素数量(在我的例子中)。
I wanted to lower the array size, but didn't worked like:
So I've tried creating a new one, with the size based on a saved count.
And then re-pass the elements in the first array to add them in the new one.
And here we have a brand new array with the exact number of elements that we want (in my case).