Stars on the Heap

Linked Lists

Following the example from the lecture implement a data structure and some basic functions to manipulate linked lists. Contrary to the lecture, your lists should hold entire star structures and not pointers.

  • Implement a type for a node in a linked list.
  • Implement a function that returns an empty list.
  • Implement a function that allows to append an element at the end of a list:
    • Use malloc to allocate memory on the heap for new list elements.
    • Be sure to handle the case of an empty list correctly.
    • Use memcpy to initialize the star structure of a newly allocated list node.
    • Check for errors and report error messages using perror/exit as usual.
  • Implement a function to free the entire memory of a list of stars:
    • Use free in your code.
    • Make sure that all list elements are freed.
    • Make sure to not use a pointer that was already freed!

Read Stars into the Heap

Rewrite the code of the function that reads all stars from the star database such that the stars are stored in a linked list instead of an array:

  • Declare a local variable with automatic storage duration holding a pointer to the list that you have implemented above.
    • Initialize it with an empty list.
  • Declare a local variable with automatic storage duration and use it to read a single star from the database.
  • Append the newly read star to the end of the list.
  • Modify the return type of the function and return the list.

Modify the main function to print all the stars in the star list returned from your function to the standard stream stdout. Don't forget to free all list elements along with their stars.

Test

Make sure that the code compiles without errors or warnings and verify that the output is the same as for your program before.