0

Basically, array should be initialized on user input. If input = 3, that means this array can store one linked list in index 0,1,2 respectively (so total 3 lists)

int input = 3;
list* array[n]//not allowed as n is not constant, also not in heap so can't pass it across functions
list* array[] = (list*) malloc(sizeof(list)*input)//compiler error

Preparing for interviews...so you can say home-work!

2
  • The question and code contradicts each other; do you want to dynamically allocate a set of lists or a set of list nodes? Commented Apr 18, 2012 at 10:19
  • array of linked list....so array[0] has listA and array[1] points to listB. in other words, instead of an array of array, i want array of linked list. But size of array has to be decided on user's input Commented Apr 18, 2012 at 17:02

3 Answers 3

1

An array of linked lists could be either an array of head nodes (assuming a standard linked list implementation) or an array of pointers to lists. In either case, the problem you seem to be facing is how to dynamically allocate an array.

The generic syntax for dynamically allocating an array on the heap is

type * array = calloc(number_of_elements, sizeof(type))

Correcting the compilation error in your code would thus be

int input = 3;
list ** array = calloc(input, sizeof(list*));

Is this what you are looking for?

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

Comments

0

It should be list* array = malloc(sizeof(list) * input), malloc returns base address of the newly allocated memory location. You can use this as the array i.e. you can access array[0]..array[input - 1].

1 Comment

But doesn't it mean that array is actually just a linked list with this much memory allocated? how would i access it index wise?
0

A (single) linked list is often a structure with a pointer to the next structure. This pattern makes it easy to add, delete and insert things from that list and still keeps the whole data usage flexible and governed in run-time.

a linked list in your situation will look like this

struct List
{
 // contents of the list
 List* Pointer_to_next_list;
};

Then you can add functions for keeping track of each list. I suggest reading Wikipedia::Linked List for how this works.

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.