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

查看:115
本文介绍了调整大小以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 *));

总是单独跟踪的大小:

Always keep track of the size separately:

long 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天全站免登陆