【发布时间】:2017-08-21 04:03:38
【问题描述】:
使用 c,我尝试将内容输入到结构数组中,一旦该数组被填充,将数组的大小加倍并继续使用 realloc。
我知道已经有人问过这样的几个问题,但我希望有人能解释清楚,因为我没有像这些问题那样创建数组并且有点困惑。
我有一个结构
struct Data {
// Some variables
}
并使用
初始化数组struct Data entries[100];
int curEntries = 100;
int counter = 1; // index, I use (counter - 1) when accessing
要重新分配,我目前正在使用
if(counter == curEntries){ // counter = index of array, curEntries = total
entries = realloc(entries, curEntries * 2);
}
我知道我需要将 realloc 强制转换为正确的东西?我只是不确定我要如何或将其转换为什么,所以我目前没有任何东西,这当然会给我错误“赋值给具有数组类型的表达式”
谢谢!
【问题讨论】:
-
您正在处理的类型是
struct Data。尝试像这样投射到它:entries = (struct Data *) realloc((struct Data *) entries, curEntries * 2); -
此外,我已经看到这通常与
malloc配对(在堆而不是堆栈中分配)。你为什么不使用它? -
数组不能是
realloc。struct Data entries[100];-->struct Data *entries = malloc(100 * sizeof *entries); -
嗯,那个铸造不起作用,但下面的答案似乎是这样做的方法。 . .至于使用malloc,我不确定第一次初始化时有什么区别,他们不做同样的事情吗?
标签: c arrays pointers memory struct