Search code examples
arrayscalgorithminsertion

How to insert a new element into an array in C?


I have an array arr of size n, and I need to insert a new element new_element at position pos. I'm looking for a solution that is efficient and adheres to best practices in C programming.


Solution

  • You could add elements if your array is big enough and you manage its actual size manually (and make sure it stays below the max allocated size). You just have to copy all the elements above the insertion point to higher locations (based on how many items you want to insert), which is very inefficient. However, unlike linked data structures, you retain the benefits of working with an array that way.

    There are data structures that combined the ~best of both worlds (more or less) by managing linked arrays, but they're more complicated to manage.