1
votes

I've been searching all day but I can't find the one that can do what I'm looking for. I'm trying to find a way to create an array of pointers.

Like the Tree data structure, but instead of just left and right pointers I want to create a expandable array that I can store many pointers. Is there a way to do this?

struct Test{
    char label[100]; 
    float fear;
    float anger;
    float disgust;
    float sad;
    float happy;
    float surprise;
    struct Test *connect[];
};

I included my struct above, so what I want is the connect to be able to expand anytime I need it and at the same time store pointers to other Tests.


I tried using malloc but it seems like I'm not doing it right, here's my attempt:

typedef struct Test test;

In the function (*tst)->connect = malloc(sizeof(test));

4
It doesn't appear you need a flexible array member. I think just a size_t n_connect; and struct Test **connect; members would be sufficient. Obviously some calloc and realloc management would be in order to maintain those members. - WhozCraig

4 Answers

1
votes

You already defined what you need:)

struct Test{
    char label[100]; 
    float fear;
    float anger;
    float disgust;
    float sad;
    float happy;
    float surprise;
    struct Test *connect[];
};

So all you need is to allocate enough memory for an object of type Test.

For example

struct Test *objext = malloc( sizeof( struct Test ) + 10 * sizeof( struct Test * ) );

Data member connect is called a flexible array member.

Only it is desurable that you would add one more data member that will contain the number of the elements in the array.

0
votes

You need to look into malloc() and memory allocations. What you are essentially looking for is

dynamic memory allocation - allocating memory on the fly.

instead of static memory - allocating memory during compile time

0
votes

You can use realloc() to increase connect size. Also use struct Test ** type for it

0
votes

When you have an FAM in a struct, it is allocated inline with the struct. You need to realloc the entire struct to resize connect.

To expand a bit, in your struct

struct Test{
    char label[100]; 
    float fear;
    float anger;
    float disgust;
    float sad;
    float happy;
    float surprise;
    struct Test *connect[];
};

the member connect is an FAM. FAMs allows you to allocate a variable sized array inline with the structure. This is generally necessary when the number of pointer dereferences needs to be minimized. However, it's slightly more complicated than keeping a simple pointer.

To realloc a structure with an FAM with additional reserved memory, call realloc as follows...

test = realloc(test, sizeof(struct Test) + fam_cur_size + fam_add_size);

The function realloc preserves existing content, and will even re-use the same memory chunk when possible.