这里有一个例子:
#include <stdlib.h>
typedef struct auxiliarRegistre { ... } clients;
int arrSize = SOME_START_SIZE;
clients *arr = malloc(arrSize * sizeof *arr);
/**
* Do stuff with arr. When you need to extend the buffer, do the following:
*/
clients *tmp = realloc(clients, sizeof *arr * (arrSize * 2));
if (tmp)
{
arr = tmp;
arrSize *= 2;
}
每次你需要扩展它是一种常见的策略时将加倍缓冲区的大小;这往往会减少拨打realloc
的电话数量。它也可能导致严重的内部碎片;如果你有128个元素,并且你只需要再存储,那么你总共分配了256个元素。您还可以通过一个固定的量来延长,如
clients *tmp = realloc(clients, sizeof *arr * (arrSize + extent));
if (tmp)
{
arr = tmp;
arrSize += extent;
}
请注意,你不想要分配的realloc
直接到你的缓冲区的结果;如果由于错误而返回NULL,那么您将失去对已分配内存的引用,导致内存泄漏。此外,您不想更新您的数组大小,直到您知道调用成功为止。
那'malloc'呼吁*一个*'client'结构分配空间。您可能还想阅读['realloc'](http://en.cppreference.com/w/c/memory/realloc)。 –
这不可能是正确的做法,因为你是铸造的malloc()''的返回值,[这是错误的(http://stackoverflow.com/questions/605845/do-i-cast-the-result -of-的malloc/605858#605858)。除此之外,你在寻找'realloc()'吗? – 2013-10-28 13:31:25
同时还要注意,你不能使用'realloc()的'以[embiggen(http://en.wiktionary.org/wiki/embiggen)'PrimaryClients',因为它不与'分配的malloc()'。 – Kninnug