[英]c, malloc and realloc an array of structs
假设我有一个名为Thing的结构。 如果我想要一个“Thing”数组,但它没有固定大小(动态),我该如何为它分配空间? 我最初是为数组本身malloc空间,然后每次向其添加元素时都必须重新分配空间吗? 例如:
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”数组中?
您可能希望使用动态阵列策略:跟踪其中的项目数量和当前容量,然后在填满时将容量加倍。 您可以获得摊销的线性时间和数组的随机访问权限。
您可以从NULL指针(Thing * thingarray = NULL;)开始,因为数组中没有任何内容。
在添加项目时,您需要为每个项目分配内存。 使用malloc作为第一个项目并使用realloc作为其他项目将起作用。
你将需要malloc它为一定数量的“东西”
说:malloc(sizeof(thing)* 8)为其中八个获得空间。
如果需要更多空间,则必须使用临时变量重新分配空间。
如果可以,请尝试使用矢量作为动态数组。 这将为您节省大量时间,您不必担心分配:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.