geoxile
geoxile

Reputation: 358

C: Structs: How do I assign the size of an array when creating an instance of the struct?

Say I have this struct

typedef struct list
{
 int index
 node *arr[]
}

Is there any way to assign the size of the node array when creating the struct of type list?

Upvotes: 0

Views: 53

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477660

If you are allocating objects dynamically, then you can use flexible arrays, which are part of C99 and later:

struct list
{
    int index;
    size_t num_elements;
    node * arr[];         // note the empty "[]"
};

Usage:

struct list * p = malloc(sizeof(struct list) + n * sizeof(node *));
p->index = 101;
p->num_elements = n;
for (size_t i = 0; i != p->num_elements; ++i)
{
    p->arr[i] = create_random_pointer();
}

// ...

free(p);

Upvotes: 5

Related Questions