2016-09-24 97 views
1

我需要帮助完成学校任务,特别是调整分配给没有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?

谢谢!

+0

请勿施放'malloc()'/'realloc()'。 – melpomene

回答

2

如果您不允许使用realloc,但mallocfree是允许的,你可以替换为以下,效率较低,顺序调用:

void *newData = malloc(newSize); 
memcpy(newData, oldData, oldSize); 
free(oldData); 

内部,realloc做同样的事情,但它的效率更高。与用户程序不同,realloc知道动态内存块的实际大小,因此它会检查是否newSize <= actualSize以避免重新分配。当actualSize不足时,realloc做与上面相同的事情。 realloc有额外的逻辑来处理尺寸需要缩小时的情况,但在您的情况下,这不适用。

+1

技术上'realloc'确实存在'memcpy(newData,oldData,min(oldSize,newSize))',但在这种情况下没有什么区别,因为大小只是持续增长。 – melpomene

+0

@melpomene对,'realloc'需要比这更聪明。但是,这应该足以满足OP,因为对于他的程序,内存分配是单向的。 – dasblinkenlight

+0

@melpomene如果您想成为技术人员,那么真正的'realloc'实现也需要在分配失败时返回原始指针,并且如果原始指针是空指针,则避免执行'memcpy'步骤。 – jamesdlin