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

查看:25
本文介绍了用 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天全站免登陆