我需要帮助完成学校任务,特别是调整分配给没有realloc的指针的内存量。C - 动态大小的结构指针数组而不使用realloc?
我在我的程序中有以下声明。
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存储器应该是这样的:
[GraphicElement的0] [1 GraphicElement的] ... [GraphicElement的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 - no realloc。可悲的是,我做这项工作的唯一方法是使用realloc。
任何人都可以指出我正确的方向来实现这只使用malloc?
谢谢!
请勿施放'malloc()'/'realloc()'。 – melpomene