gpt4 book ai didi

C - 不使用 realloc 的动态大小的结构指针数组?

转载 作者:太空宇宙 更新时间:2023-11-04 02:34:16 25 4
gpt4 key购买 nike

我需要学校作业方面的帮助,特别是在不重新分配的情况下调整为指针分配的内存量。

我的程序中有以下声明。

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 来实现它吗?

谢谢!

最佳答案

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

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

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

关于C - 不使用 realloc 的动态大小的结构指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39675057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com