Home > Software engineering >  In C , adding element to dynamic array is done by creating a new array. In languages like Python, d
In C , adding element to dynamic array is done by creating a new array. In languages like Python, d

Time:08-16

I used many programming languages that had something like .push() or .append() to add an object to the end of a dynamic array. Now, I learnt some C and noticed that it does not support that, but I instead have to implement a function that manually does this, and this function creates a new temporary array that is one element longer, loops through the old array and copies each element, adds the new object, deletes the old array, and copies the temporary array to the old array. Does the languages I already worked with that allow functions like .push() do the same thing at the assembly level?

CodePudding user response:

In C , we also have constructs that do their own memory management: std::vector<> comes to mind. It is advisable to be used over plain arrays when appropriate. std::vector<> maintains a buffer and resizes moves only when necessary (i.e., when the buffer is too small to hold the newly inserted element); then it expands usually to double or similarly.

In other languages, you also need to implement some kind of memory management. However, it's not trivial whether this kind of resizing is necessary: for most scripting languages are actually implemented in a lower-level language, very usually C/C /C--. So it's possible that std::vector<> (or even std::map<>) is used in the background. However, at the end of the day, someone must implement resizing 1, as memory is usually viewed as a one-dimensional array from which you allocate; you can't necessarily extend an allocation infinitely.

1 Note: theoretically, on some architectures it'd be possible to delegate this to virtual memory management and use segment registers for pointers, index registers for offsets, and let paging associate segment:index to physical addresses; however, that's rarely used nowadays.

CodePudding user response:

Yes they do. For example python list (which are arrays, not lists) is doing exactly the same.

Note: You do not have to implement this yourself. That's what the STL is for in C and the relevant data structure for a dynamic array is std::vector. Except std::vector is smarter about growing the array, growing it by more than one element so not every push has to copy all the previous data. In fact it has ammortised cost of O(1) per push. If you know how much data you have it's still best to reserve the right amount of space from the start though.

  • Related