I have a standard array that sometimes needs to grow so I use realloc.
My problem is the following:
Imagine I have an array with one position that contains a valid object. Now I have a new object that I want to add to the array, but I want it to be in the position, say, 14. I use realloc to get a 15 slots array (0 to 14)
and put the new object in position 14. But now I want all the other positions that originally did not contain valid objects to be set to NULL. Unfortunately realloc does not do that automatically. Do you guys have a suggestion on how to do it? In other words, how do I loop through the new array and check to see which are valid objects and which are not so I can set those invalid to NULL?
IMO, this is one of the few advantages of using a language that has pointer arithmetic. Simply calculate the range you want to null out, and call bzero() or memset() -- with many compilers, these functions should be mapped to use the processor block instructions.
As for "checking for valid objects"? Do you really need to do that? You just need to zero out any memory that wasn't part of the original array (when array is extended), and zero out the location of the original element that you moved.