Reputation: 1904
Let's say I have a struct called Thing. If I want to have an array of "Thing", yet it doesn't have a fixed size (dynamic), how do I go about allocating space for it? Do I initially malloc space for the array itself, and then have to realloc space every time I add an element to it? For example:
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;
How do I set up malloc and realloc to be able to add as many elements of type Thing to the array of "Thing"?
Upvotes: 0
Views: 2491
Reputation: 386
If you can, try using a vector for dynamic arrays. It will save you a lot of time and you don’t have to worry about allocation:
#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;
}
Upvotes: -1
Reputation: 56059
You'll probably want to use the dynamic array strategy: keep track of how many items are in it and the current capacity, then any time it fills up, double the capacity. You get amortized linear time and the random access of an array.
Upvotes: 3
Reputation: 4539
You will need to malloc it for a certain amount of "Things"
Say: malloc(sizeof(thing)*8) to get space for eight of them.
If you need more space, you will have to reallocate space using a temp variable.
Upvotes: 0
Reputation: 23
You can start with a NULL pointer (Thing *thingarray = NULL;) since there is nothing in the array.
As you add items you will need to allocate memory for each item. Using malloc for the first item and realloc for additional items would work.
Upvotes: 0