1

I'm a first-year B.Tech student currently learning C programming. I'm working on a project that involves handling a collection of data, and I'm a bit confused about when to use arrays and when to use linked lists. Can someone explain the key differences between arrays and linked lists in C, and in what scenarios one would be preferred over the other? Additionally, any practical examples or coding exercises would be greatly helpful for better understanding. Thanks!

currently learning C language

5
  • When the length of data is known and fixed, I use an array. If the length of data is unknown or may grow, then a linked list is nice because it is easily grown by adding items -- and can be shrunk easily too (by removing items). Commented Nov 25, 2023 at 17:45
  • I would argue that even when the size is not fixed something like a dynamic array is usually still, better due to the memory of the data being contiguous, which makes it more cache friendly when iterating. The only real case where I think a linked list could outshine an array is in the very specific case where you need to iterate through a list and insert and remove elements frequently while iterating. Commented Nov 25, 2023 at 18:04
  • I would advise you to use a dynamic array (or regular array, if you know the amount of data beforehand) by default and if you think a linked list could be faster, you could implement both, test both and compare the performance. Commented Nov 25, 2023 at 18:05
  • There are also very specific cases where you may not be able to afford the resize cost, dynamic arrays occasionally have (when the array is full and a new element needs to be added). If you need adding elements to be responsive at all times and not just on average, you might also want to use a linked list. Commented Nov 25, 2023 at 18:14
  • If you need to keep the sequence ordered as you add or remove elements, or if you need to regularly add or remove elements at arbitrary locations, use a list (or a tree). If you need random access, or only need to add data at the end, or all data is loaded once on startup, use an array. Commented Nov 26, 2023 at 13:27

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.