Home > Software engineering >  create flexible array size in struct
create flexible array size in struct

Time:12-30

hi there I have these structs code
I need to make my head[] array size flexible
for example, if my head array size is 9 how can I extend it to be 10 ?!

struct Graph
{
  // An array of pointers to Node to represent an adjacency list
  struct Node *head[N];
};

// Data structure to store adjacency list nodes of the graph
struct Node
{
  int dest, weight;
  struct Node *next;
};

how can I create a struct graph with a flexible head array size?

CodePudding user response:

A struct with a flexible array member usually has a member keeping track of what size the array is, so I'm assuming it looks like this:

struct Graph {
    size_t nodes;
    struct Node *head[];
};

To allocate memory for such a struct you would need to call malloc and sum up the sizeof(Graph) (where the extent of the flexible member is counted as 0) and the sizeof(struct Node*[the_number_of_node_pointers_you_want]).

Example:

struct Graph *Graph_create(size_t nodes) {
    struct Graph *g = malloc(sizeof *g   sizeof(struct Node*[nodes]));
    if(g) g->nodes = nodes;
    return g;
}

If you later want to expand the flexible array, you could use realloc in a similar way:

// this returns true or false depending on if expansion succeeded
bool Graph_expand(struct Graph **g, size_t nodes) {
    if(*g && (*g)->nodes < nodes) {
        struct Graph *ng = realloc(*g, sizeof *ng   sizeof(struct Node*[nodes]));
        if(ng) {
            *g = ng;
            (*g)->nodes = nodes;
            return true;
        }
    }
    return false;
}

Demo

A word of caution when it comes to expanding the array: realloc may move the memory if it can't expand the allocation in-place. If that happens and you have any pointers to your old Graph object, they will have been invalidated by that realloc.

  • Related