PGOnTheGo
PGOnTheGo

Reputation: 805

storing multiple arrays within a struct in C

I am trying to design a data structure in C where I can store multiple arrays possibly in a struct, where each of the arrays are of a different size. For example:

typedef struct task_list
{
  int total_tasks;
  unsigned int *task_array
 }task_list;

typedef struct node_list
{
  int total_nodes;
  task_list *array_node
 }node_list;

Therefore if I have 5 nodes, then total_nodes will be 5 and I wish to have 5 subsequent arrays namely array_node[0], array_node[1] ... array_node[4]. Each of the arrays hold unsigned integers(tasks). The problem is each of these arrays hold a different number of tasks (total_tasks in struct task_list), therefore the size of each of the arrays will be different.

How do I create and allocate memory for each of these task array's? and what would be the best way to access them later?

Upvotes: 0

Views: 1442

Answers (3)

jxh
jxh

Reputation: 70392

You should modify node_list so that it maintains an array of pointers to task_list:

typedef struct node_list
{
  int total_nodes;
  task_list **array_node;
 }node_list;

Now, if you need 5 task lists, you allocate room for 5 pointers to task_list first.

node_list n;
n.total_nodes = 5;
n.array_node = malloc(n.total_nodes * sizeof(task_list *));

Then, you iterate through each array_node, and allocate an appropriately sized task_list.

for (i = 0; i < n.total_nodes; ++i) {
    n.array_node[i] = allocate_task_list(task_list_size(i));
}

Then, to get to the ith task_list:

task_list *tl = n.array_node[i];

Upvotes: 0

1&#39;&#39;
1&#39;&#39;

Reputation: 27095

You need to allocate a node_list, then allocate its array_node to hold 5 task_lists, then allocate each of the task_lists' task_arrays to hold a variable number of tasks (using malloc(total_tasks) * sizeof(unsigned int))).

Upvotes: 1

Jiminion
Jiminion

Reputation: 5168

If they are 1-D arrays, best way to allocate memory is through malloc. Again, since they are 1-D you can access them via array notation, being careful no to exceed the bounds given by total_nodes and total_tasks. Use free to free up arrays when deleting nodes. If array nodes gets bigger, use realloc to make the array bigger and keep the old pointers in place.

Upvotes: 1

Related Questions