I'm trying to write the equivalent of remove for Java's ArrayList in C.
Here is my code. It assumes that index is a valid index in the list.
void arrayListRemove(ArrayList* list, int index){
int i;
if (arrayListSize(list)==1){
list->size = 0;
free(list->data);
list->data = NULL;
} else {
for(i=index;i<arrayListSize(list)-1;i++){
list->data[i] = list->data[i+1];
}
list->data = realloc(list->data, (arrayListSize(list) - 1) * sizeof(void*));
if (list->data != NULL){
--list->size;
} else {
exit(1);
}
}
}
Is this correct?
Would the code work without the arrayListSize(list) == 1 check? I.e. does realloc(list->data, 0) free the arrayList? I've seen conflicting things online about what realloc(ptr, 0) would do.
sizeof(void*)bysizeof list->data[0]. If the list is unordered, it is cheaper to replace the deleted element by the last element in the array. Finally: if index is beyond the size, you still decrement the size, which looks wrong.