Lets say I have an array of structs and I want to delete an entry that has a struct with an entry matching some criteria.
This array is dynamically allocated with malloc, I keep the element count in a separate variable.
How do I go about deleting the entry?
I’m thinking of
for (i = pos; i < arr_len; i++) {
arr[i] = arr[i+1];
}
arr_len--;
But this leaves the same amount of memory for the array while I actually need less and an orphan (sort of) last entry.
Is issuing a realloc in such situation an accepted practice? Would realloc do memcpy in this case? (shortening the allocated memory by one block).
reallocis ok … but keep reading 🙂reallocwill not move parts of the memory; it may move the whole block. So you need to copy the data before changing the allocated size.To move the data,
memmove(notmemcpy) is a good option: it works for memory areas that belong to the same object. Pay attention to not go over your array limits, though; like you do in your code.The
arr[i] = arr[i + 1];will try to access one past the allowed size. You needThere is somewhat of an overhead when calling
realloc. If your structs are not large and/or they live only for a short while, consider keeping both an element count and allocated count and only realloc to enlarge (when(element_count + 1) > (allocated_count)).If the struct is large, also consider a different data structure (linked list perhaps).