用C调整数组大小

编程入门 行业动态 更新时间:2024-10-28 09:20:16
本文介绍了用C调整数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要在一个游戏中有一个结构体数组,但是我不想将数组限制为固定的大小。我被告知有一种方法可以使用realloc来使数组更大,当它需要时,但是找不到任何这样的工作示例。

I need to have an array of structs in a game I'm making - but I don't want to limit the array to a fixed size. I'm told there is a way to use realloc to make the array bigger when it needs to, but can't find any working examples of this.

有人可以请告诉我如何做到这一点?

Could someone please show me how to do this?

推荐答案

开始创建数组:

structName ** sarray = (structName **) malloc(0 * sizeof(structName *));

请始终跟踪尺寸:

size_t sarray_len = 0;

要增加或截断:

sarray = (structName **) realloc(sarray, (sarray_len + offset) * sizeof(structName *));

然后设置大小:

sarray_len += offset;

快乐帮助,希望有所帮助。

Happy to help and hope that helps.

更多推荐

用C调整数组大小

本文发布于:2023-11-30 11:16:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649779.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   大小

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!