Reputation: 67
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.
Upvotes: -12
Views: 610
Reputation: 19736
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.
Upvotes: 0
Reputation:
You cant add new elements on arrays on C programming. You need to create linked lists for a dynamic list.
After you learn how to build structures, you can start checking out data structures (What is a Data Structure?) which include Linked lists. Then you can start working on Linked Lists (What is a Linked List?) so you can build dynamic lists.
Hope this would be helpful
Upvotes: 0
Reputation: 13979
As already mentioned, you can't add any new element in the array, try to use a linked list instead.
Upvotes: 3