如何重新分配结构数组 [英] How to realloc an array of structs

查看:81
本文介绍了如何重新分配结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用c,我试图将内容输入到一个结构数组中,一旦该数组被填充,请将该数组的大小加倍并继续使用realloc.

Using c, I'm trying to input stuff into an array of structs, and once that array is filled, double the size of the array and keep going, using realloc.

我知道已经有这样的问题了,但是我希望有人能清楚地解释它,因为我没有像那些问题那样创建数组,并且感到有些困惑.

I know there's been several question like this asked already, but I was hoping someone could explain it clearly since I didn't create my array the way those questions did and am getting a bit confused.

我有一个结构

struct Data {
    // Some variables
}

并使用

struct Data entries[100];
int curEntries = 100;
int counter = 1; // index, I use (counter - 1) when accessing

要重新分配,我正在使用

To realloc, I'm currently using

if(counter == curEntries){  // counter = index of array, curEntries = total
    entries = realloc(entries, curEntries * 2);
}

我知道我需要将realloc强制转换为正确的东西吗?我只是不确定将其强制转换为什么或打算使用什么,所以我目前还没有任何东西,这当然给了我错误分配给具有数组类型的表达式的信息"

I know I need to cast realloc to something right? I'm just not sure how or what I'm meant to be casting it to, so I currently don't have anything, which of course gives me the error "assignment to expression with array type"

谢谢!

推荐答案

struct Data entries[100];// memory is already allocated to this

您需要将 entries 声明为指针,例如:

You need to declare entries as pointer like:

struct Data *entries=NULL;
entries = malloc(curEntries  * sizeof(struct Data));
//When its time to reallocate
entries = realloc(entries, (curEntries * 2 * sizeof(struct Data)));

这篇关于如何重新分配结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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