Which one of the following aproaches is the best one to implement a dynamic array in C? Array objects vs array of pointers to objects?

  Kiến thức lập trình

I was trying to implement a dynamic array in C, much like Arraylist of Java. The initial idea was to use an array of the actual objects to avoid side effects(having dangling pointers) whenever a object is delete from outside of the arraylist and have all the object preallocated, that is, instead using array of pointers and having of them living in a fragmented memory locations and having to use a loop to deallocated each one of them one by one, I wanted them to be stored in contiguous manner so that I could delete all of them at once with a single call to free.

So my concern is, if I used the approach of contiguous allocation, every time created a new object to be added to the list, I will end up having duplicate data/objects, so wasting memory and having to manually deallocate the outside objects.

On the other way round, if use the array of pointer approach, it’ll use little less memory(no duplicate data/objects) but the allocation and deletion of the multiple objects in list becomes much more slower due to one more level of pointer indirection and if someone deletes one of more objects from the outside, the list is going to have danglings pointers opening the door to all types memory bugs.

So I got stuck trying to decide which one of the approaches I should use to make efficient use of memory and be performant at the same time.

What are the cons an pros of each approaches and which one suits best?

Any help,tips or advice would be greatly appreciated. Thanks

Obs1: I am new to programming and C world.
Obs2: I am not working in any specific project, I’m just practicing data structure implementation using C.
Obs3: English is not my native language, so I apologize for the mistake and typos.

Implement a dynamic array in C

New contributor

Spencer Sumboh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.