0

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?

2
  • "... where I can store multiple arrays possibly in a struct, where each of the arrays are of a different size ...", this is not possible as you worded it, however you could have an array of void pointers that points to different arrays of different sizes (and lengths). Commented Aug 12, 2013 at 19:14
  • Using the structures you have already, the only problem I see is total_nodes should be total_task_lists. Everything else is straight up if you think about it hard enough. Commented Aug 12, 2013 at 19:17

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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))).

Comments

0

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.