I am writing a heap data structure in C. Theres one thing that I can’t decide on. I am implementing it as an array. The way it works, is that function “insert” takes a pointer to some data and copies all bytes of that data, pointed to, into the array, is that a good approach? Or should I just store the pointer itself, the function was called with?
Share
Well, you have to consider that the memory pointed to will probably be changed or become invalid, for example when it’s a variable on the stack. So in most cases, it would not be a good idea to just store the pointer.
If you must have a function insert() there is no way around copying the memory – although this is slow. Best is to use memcpy(), because this is still the fastest function.
Heaps are usually designed a bit differently: You have a function malloc(int size) that you call to retrieve a pointer to a memory area of desired size. There you can store whatever you need it for.