A couple of days ago I asked myself which data-structure I should in a function in C.
I usually write in C++ and the choice would have fallen to std::vector.
There a some possible choices:
- a static (big enough) array
- a dynamic array which grows when needed(e.g. doubling its size)
- an own list implementation as struct with a pointer next
The last option seems to be unusual. Are there any bigger project where
someone uses own structures like lists?
Is there a general rule for the decision between array or own
data-structures?
When I would need a tree structure I wouldn’t think twice an just write a tree.
Are there any widely used libs with such structures(like boost for C++)?
Or is this considered as bad style because you would have to store a void* instead of
the actual type?
Thank a lot for your experience!
Each has its own advantages and disadvantages.
Static arrays: perfect for lookup tables and data that doesn’t change its size throughout the program execution. They get allocated on program startup, so you don’t have to manage this memory in any way. A disadvantage is that you cannot resize or free a static array – it stays there until the program terminates.
Dynamically growing arrays: an easy to manage data structure that can almost be a substitute for vector arrays in C++. A disadvantage is the overhead of allocating memory at runtime, but that can be alleviated if you allocate bigger chunks at once.
Linked lists: take care if you are going to have a lot of elements because allocating each one separately without using a memory pool can lead to memory waste and fragmentation.