Andrew Backes
Andrew Backes

Reputation: 1904

c, malloc and realloc an array of structs

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

Answers (4)

Petr Dokoupil
Petr Dokoupil

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

Kevin
Kevin

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

Jacobm001
Jacobm001

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

Terminal
Terminal

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

Related Questions