用C调整数组大小 [英] Resizing an array with C

查看:146
本文介绍了用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调整数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆