0

假设我有一个名为 Thing 的结构。如果我想要一个“事物”数组,但它没有固定大小(动态),我该如何为它分配空间?我是否最初为数组本身分配空间,然后每次向其中添加元素时都必须重新分配空间?例如:

struct Thing{
    char *stuff;
    char **morestuff;
    int evenmorestuff;
};

Thing *thingarray;
thingarray = malloc(sizeof(Thing));

....

//And then allocating space for elements, which will get called an unknown amount of times
Thing j;
thingarray[count] = j;

如何设置 malloc 和 realloc 以便能够将尽可能多的 Thing 类型的元素添加到“Thing”数组中?

4

4 回答 4

3

您可能希望使用动态数组策略:跟踪其中有多少项目和当前容量,然后在它填满时,将容量加倍。您将获得摊销的线性时间和数组的随机访问。

于 2012-09-27T23:54:50.140 回答
0

您可以从 NULL 指针 (Thing *thingarray = NULL;) 开始,因为数组中没有任何内容。

添加项目时,您需要为每个项目分配内存。对第一个项目使用 malloc 并为其他项目使用 realloc 将起作用。

于 2012-09-27T23:52:53.393 回答
0

您将需要为一定数量的“事物”分配它

说: malloc(sizeof(thing)*8) 以获得其中八个的空间。

如果您需要更多空间,则必须使用临时变量重新分配空间。

于 2012-09-27T23:54:45.560 回答
-1

如果可以,请尝试将向量用于动态数组。它将为您节省大量时间,并且您不必担心分配问题:

#include <vector>
using namespace std;

struct Thing
{
    char *stuff; 
    char **morestuff; 
    int evenmorestuff; 
};

int _tmain(int argc, _TCHAR* argv[])
{
    vector<Thing> vt;

    char stuff = 'a';
    char *morestuff = "abc";

    Thing t;
    t.stuff = &stuff;
    t.morestuff = &morestuff;
    t.evenmorestuff = 0;

    int count = 10;
    for (int i = 0; i <= count; ++i)
    {
        t.evenmorestuff = i;
        vt.push_back(t);
    }

    Thing j; 
    j.stuff = &stuff;
    j.morestuff = &morestuff;
    j.evenmorestuff = 0;

    vt[count] = j; 

    return 0;
}
于 2012-09-28T00:34:13.707 回答