【发布时间】:2016-09-24 09:59:41
【问题描述】:
我在学校作业方面需要帮助,特别是调整分配给没有重新分配的指针的内存量。
我的程序中有以下声明。
struct GraphicElement
{
enum{ SIZE = 256 };
unsigned int numLines;
Line* pLines;
char name[SIZE];
};
typedef struct
{
unsigned int numGraphicElements;
GraphicElement* pElements;
}VectorGraphic;
VectorGraphic Image;
随着程序的运行,我将向 pElements 添加更多 GraphicElements。
例如,经过 5 次迭代后,pElements 的内存应该是这样的:
[图形元素 0][图形元素 1] ... [图形元素 4]
对于函数 AddGraphicElement(VectorGraphic* vg) 我有这段代码(为了便于阅读,删除了一些行):
vg->pElements = (GraphicElement*)realloc(vg->pElements, sizeof(GraphicElement)*(vg->numGraphicElements+1));
//Then I assign inputs from user into the members of the struct at vg->pElements[vg->numGraphicElements]
vg->numGraphicElements++;
这行得通,但是根据我教授的指示,我只能使用 malloc 和 free - 不能使用 realloc。可悲的是,我完成这项工作的唯一方法是使用 realloc。
谁能指出我只使用 malloc 来实现这一点的正确方向?
谢谢!
【问题讨论】:
-
不要投射
malloc()/realloc()。
标签: c arrays pointers malloc realloc