0

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?

1
  • There are a few problems with this definition. 1) missing ';' and end of field line. 2) missing ';' and end of the struct definition, after the closing brace'}' 3) this typedef is incomplete, because there is no name defined after the closing brace ';' And generally, it is better to define a struct, NOT a typedef that may be seen as a struct. Commented Dec 15, 2014 at 2:53

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Is there anything if I don't want to allocate it dynamically? Also, is this safe to create an array of these linkLists?
@geoxile: No, and no. You can only use this for dynamic allocations. you cannot have variables or any kind of expression whose type is a struct with flexible array member. Maybe you can use a plain variable-length array for your needs?
@KerrekSB: I vaguely recall that in at least some compilers one could initialize a struct with a VLA member [in which case the size of the last member would be inferred by the initialization] but I'm not sure; do you recall any such thing?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.